A simple diagram of the SQL Injection risk path
Risk path: an input or context crosses a security boundary.
A simple three-step test path for SQL Injection
Testing path: establish a baseline, make one controlled change, and verify the effect.

Issue

SQL injection occurs when an application builds a database query by combining SQL instructions with untrusted input, and that input can change the meaning of the query. For example, an application might add a search term directly to a SQL string. If the term is not kept separate from the SQL instructions, specially crafted input may alter the query’s conditions or operations. OWASP’s SQL Injection Prevention Cheat Sheet and MITRE CWE-89 describe this as a failure to keep data separate from SQL commands.

The main cause is unsafe query construction, often through string concatenation. SQL injection can also occur in code that uses an ORM (object-relational mapper) if it inserts untrusted input into raw SQL. A database error after unusual input may be a clue, but it does not by itself prove SQL injection.

Parameterized queries prevent input values from being interpreted as SQL instructions: the query structure is set separately, and values are passed to the database through parameters. This is the primary defense recommended by OWASP. Stored procedures can also be safe when they keep values separate from dynamically constructed SQL.

Examples

Compare unsafe query construction with parameter binding:

Unsafe query construction:

# Vulnerable: input becomes part of the SQL text.
sql = "SELECT id, name FROM products WHERE name = '" + product_name + "'"
cursor.execute(sql)

Parameterized query:

# Safer: SQL structure and input value are sent separately.
cursor.execute(
    "SELECT id, name FROM products WHERE name = ?",
    (product_name,),
)

Use the database driver’s documented parameter-binding API; placeholder syntax varies, and not every driver uses ?. Confirm injection by showing that controlled input changes query behavior, not merely by observing an error.

Impact

If an attacker can change a query, the consequences depend on what the query does, which data it can reach, and the privileges of the application’s database account. Possible outcomes include viewing records the user should not see or altering or deleting data. More serious database or operating-system effects require additional database features, permissions, and configuration; they should not be assumed from an error message or an unconfirmed injection indicator. OWASP’s testing guide describes several forms of SQL injection and notes that the available impact depends on the application and database.

A confirmed injection flaw does not automatically mean that authentication can be bypassed, accounts can be taken over, or all database contents can be extracted. Those claims require evidence that the vulnerable query and the attacker’s access actually permit those outcomes.

Testing

1. Check whether input changes query behavior

Compare a normal input with a controlled expression in a test dataset. Observe whether the result or authorization decision changes in a way consistent with the query.

Example: A database error is a useful clue. Verify an actual change in the query result or decision before reporting impact.

GET /products?id=1%20AND%201%3D1 HTTP/1.1
Host: app.example.test

2. Compare true and false conditions

Send two otherwise identical inputs representing true and false conditions. Repeat and compare status, body, and application state to rule out unrelated behavior.

Example: A search with known test records provides a stable comparison. A single unusual response can have another cause.

GET /products?id=1%20AND%201%3D2 HTTP/1.1
Host: app.example.test

3. Review inputs and query construction

Check relevant query parameters, JSON fields, headers, and stored values that later reach database queries. If code is available, inspect parameterized queries and any dynamic identifiers.

Example: A parameterized value does not protect a separately concatenated table name. Review each query component.

4. Compare timing when responses look identical

Where the test environment supports it, compare repeated baseline requests with a bounded timing check appropriate to the database. Record response times and correlate with server or database logs where available.

Example: Network delays can make a single request slow. A repeatable difference still needs evidence that the database query caused it.

Common false positives include generic server errors, input validation messages, changed search results caused by ordinary search behavior, and inconsistent timing. Conversely, the absence of a visible database error does not prove that input is safe: applications may suppress errors or return the same page for different database outcomes.

Mitigation

Primary fix: use parameterized queries for values. Replace concatenated SQL with prepared statements or the database driver’s parameter-binding API. Review all code paths that build queries, including ORM raw-query methods and stored procedures that construct dynamic SQL. Verify the fix by checking that user-controlled values are passed as parameters and by retesting the affected input with ordinary and SQL-syntax-containing values.

For dynamic identifiers, use a strict allow-list. Bind parameters generally represent data values; they do not safely substitute table names, column names, or SQL keywords such as sort direction. Map each permitted choice to a fixed, developer-defined SQL fragment. For example:

sort_columns = {
    "name": "name",
    "price": "price",
}
column = sort_columns.get(requested_sort, "name")
 
sql = f"SELECT id, name, price FROM products ORDER BY {column}"
cursor.execute(sql)

Here, only values selected from the fixed mapping enter the SQL text. Do not append a raw user-supplied identifier or sort expression. OWASP’s guidance treats allow-list validation as useful where parameters cannot be used, while emphasizing parameterized queries as the preferred defense.

Use input validation as an additional safeguard. Validate that inputs match their expected format—for example, that an ID is an integer or a sort choice is one of the supported options. Validation helps reject invalid values, but it does not replace parameter binding. Escaping or removing punctuation is fragile and can break valid input; it should not be the main fix.

Limit database privileges. Give each application database account only the permissions it needs. A read-only feature should not connect with an account that can modify tables or administer the database. Least privilege limits potential damage if another flaw is exploited; it does not prevent SQL injection itself. OWASP’s prevention guidance recommends least privilege as a defense-in-depth measure.

Retest and handle errors safely. After changing query construction, retest the original input paths and confirm that input is treated as data and does not alter query logic. Return generic error messages to users, while recording useful diagnostic details in protected server-side logs. Suppressing database errors can reduce information exposed to users, but it does not repair an unsafe query.

Sources