SQL injection: when input becomes part of the query

SQL injection (SQLi) is an attack in which input sent to an application ends up inside a database query and changes what the query does. It can read data the user should not see, change or delete records, and sometimes reach the server behind the database. It is preventable with one well-known technique, and still common.

Section Web attacks Updated Weakness CWE-89

Quick facts

Weakness
CWE-89: improper neutralization of special elements in an SQL command
OWASP category
A05:2025 Injection
Impact
Reading, changing or deleting data; bypassing sign-in; in some setups, commands on the database server
Main fix
Parameterised queries (prepared statements)
Does a WAF stop it?
Mostly. Query syntax in the request is recognisable; the vulnerable query stays in the code until fixed

Definitions follow OWASP and CWE-89.

How SQL injection works

An application builds a query by joining strings: the fixed part written by the developer, and a value taken from the request, such as an account number or a search term. If the value is joined in as text, the database cannot tell where the developer's query ends and the user's input begins.

An attacker sends input that contains SQL syntax: a quote that closes the string, an operator that changes the condition, or a clause that adds a second query. The database runs the result as one command. OWASP's standard example turns a lookup for one account into a lookup that returns every account by adding a condition that is always true.

Types of SQL injection

  • In-band SQL injection. Results come back in the application's own response, either as data (union-based) or in database error messages (error-based).
  • Blind SQL injection. Nothing is shown; the attacker infers answers from whether a page changes (boolean-based) or how long it takes to respond (time-based).
  • Out-of-band SQL injection. The database is made to send data through another channel, such as a DNS or HTTP request to a server the attacker controls.
  • Second-order SQL injection. Input is stored safely first and only becomes part of a query later, in a different feature that trusts stored data.

The types differ in how data leaves, not in the cause: in every case input was joined into a query as text. The same mix-up of instructions and data is behind prompt injection in language-model features. The same mistake in non-relational databases is covered under NoSQL injection. Directory queries have an equivalent in LDAP injection.

WHAT EACH TYPE LEAVES BEHIND SYNTAX IN THE REQUEST RESULT IN THE RESPONSE FIXED BY PARAMETERS IN-BAND (UNION, ERROR) BLIND (BOOLEAN, TIME) OUT-OF-BAND SECOND-ORDER // every row ends in the same fix
// four types, one cause and one fix

Blind SQL injection: boolean-based and time-based

In blind SQL injection the application is vulnerable, but its responses contain neither the results of the query nor database error text, so there is nothing to read. The attacker learns what the database holds by asking yes-or-no questions and watching what changes.

  • Boolean-based. The same request is sent twice, once with a condition that is true and once with one that is false, such as ' AND '1'='1 against ' AND '1'='2. If the page differs between the two, the page has answered the question.
  • Time-based. When the page looks the same either way, the attacker adds a condition that makes the database pause, and reads the answer from the response time. The delay function depends on the database: pg_sleep in PostgreSQL, SLEEP in MySQL, WAITFOR DELAY in SQL Server.

Each question gives one answer, so data is retrieved one character at a time. Done by hand this is very slow, which is why attackers use tools that automate it. The trace is a long run of near-identical requests to one parameter. A WAF can refuse the query syntax in each of them and rate limiting can slow the run; neither fixes the query. Blind injection is closed like any other, with parameterised queries. Hiding database errors does not make a query safe; it only makes the injection blind.

What it looks like in a request

Most SQL injection attempts carry characters that have no business in the field: quotes in a numeric identifier, comment markers, keywords such as UNION or SELECT in a search box, or operators that build a condition. Automated scanners send many of these in a short time, which also shows in the request rate.

Legitimate text can contain the same characters. A support ticket quoting a query or a name with an apostrophe looks similar to a filter, which is why rules for SQL injection are scored and tuned per site. The markup that cross-site scripting needs raises the same trade-off for XSS rules.

SQL injection example in PHP

A vulnerable lookup joins the input into the query: $db->query("SELECT * FROM users WHERE email = '" . $_GET['email'] . "'"). An email value of ' OR '1'='1 turns the condition into one that is always true, and the query returns every user. The value arrives through $_GET, the query string of the URL, so this is SQL injection via URL.

The fixed version sends the query and the value separately, as a prepared statement: $stmt = $db->prepare('SELECT * FROM users WHERE email = ?'); $stmt->execute([$_GET['email']]);. The database receives the value as data, so quotes in it are just characters. The same pattern exists in every language; the OWASP Query Parameterization Cheat Sheet shows it for each.

What a WAF catches, and what it misses

A request filter matches the shapes above and can refuse them before they reach the code; rule sets such as the OWASP Core Rule Set keep a dedicated group of rules for it. That protects an injectable query while it is being fixed.

It misses what does not look like SQL in the request: second-order injection, input encoded in a way the rules do not decode, and injection through channels the filter does not read. And it leaves the query vulnerable, so the next variation may get through. Injection that reaches an operating-system shell instead of a database is command injection.

How to prevent SQL injection

To mitigate SQL injection, start with the first item, which closes the hole. The rest are layers that defend against what slips through.

  1. Use parameterised queries. Prepared statements send the query and the values separately, so input can never become syntax. The OWASP SQL Injection Prevention Cheat Sheet puts this first.
  2. Use stored procedures carefully. They help only if they do not build SQL from strings inside.
  3. Validate input against what is allowed. An allow-list for things that cannot be parameters, such as column names or sort order.
  4. Give the database account the least privilege it needs. So an injection that slips through can read less and change nothing it should not.
  5. Do not show database errors to users. Error text helps attackers map the query.

ORMs and SQL injection

An object-relational mapper builds parameterised queries for ordinary lookups, which removes most SQL injection. The risk returns wherever the code steps outside it: raw query functions, fragments of SQL passed as strings, and features that take a column or table name from input.

Names cannot be sent as parameters, so a sort order chosen by the visitor, such as ORDER BY a column from the query string, has to be checked against a fixed list of allowed columns. That one case accounts for a large share of injection in applications that otherwise use an ORM throughout.

Questions

What is SQL injection?

SQL injection is an attack in which input sent to an application becomes part of a database query and changes what it does, letting an attacker read, change or delete data.

How do you prevent SQL injection?

Use parameterised queries, also called prepared statements, so input is never treated as SQL. Add allow-list validation for values that cannot be parameters, least-privilege database accounts, and generic error messages.

What is blind SQL injection?

Blind SQL injection is SQL injection where the application shows no query results or errors, so the attacker infers answers from whether a page changes or how long it takes to respond.

How does time-based blind SQL injection work?

The attacker adds a condition that makes the database pause before it answers, then reads the response time: a long wait means the condition was true. It is used when the page looks the same whether the condition is true or false.

Can a WAF prevent SQL injection?

A WAF can refuse many SQL injection attempts by matching query syntax in requests, which protects vulnerable code while it is fixed. It does not make the query safe; parameterised queries do.