# SQL Injection Prevention: Parameterized Queries, ORMs, and Verification

> Stop SQL injection with bound parameters in PostgreSQL and MySQL, safe ORM patterns, allowlisted identifiers, least privilege, and a testable pass checklist.

**Quick answer:** SQL injection happens when input is concatenated into SQL text. The durable fix is to keep the statement text constant and bind every value as a parameter in PostgreSQL or MySQL. Allowlist identifiers such as table names and sort columns, review ORM raw fragments, restrict database privileges, and verify with harmless payloads in a disposable environment.

## Key takeaways

- Injection is a grammar problem: once input can add quotes, operators, or statement separators, the database cannot tell data from code.
- Parameterized queries and server-side prepared statements send values outside the SQL text, so payload syntax is never parsed.
- Placeholders cover values only; table names, column names, sort direction, and operators need a fixed allowlist mapping.
- ORMs bind by default but expose raw escape hatches, and stored procedures reintroduce the same risk when they build dynamic SQL.
- Least privilege, non-leaking errors, and a payload test suite limit damage and prove that the fix works.

---

SQL injection is not a parsing accident. It is what happens when an application assembles a SQL string from data, and the database has no way to tell which characters were meant as syntax and which as content. The fix is structural rather than cosmetic: keep the statement text fixed and send every value through a binding channel.

This guide covers how concatenation creates the bug, how parameterized queries and prepared statements remove it in PostgreSQL and MySQL, where ORMs and stored procedures reopen it, and how to verify a fix with payload tests, privilege checks, and honest pass criteria.

## How concatenation turns data into SQL

A vulnerable query usually starts as a convenience. The developer needs a filter, so the request value is placed inside a template literal or a string concatenation, and the result is handed to the driver. If the input is `x' OR '1'='1`, the parser sees a boolean expression that is true for every row. If the input is `x'; DROP TABLE orders; --`, and the driver permits multiple statements, the second statement runs. If the input is `1 UNION SELECT password FROM users`, rows appear where the caller expected a product list.

Numeric positions are just as exposed. `WHERE id = ` followed by `0 OR 1=1` needs no quote at all, which is why "we only accept numbers" is a weaker defense than it sounds. Identifier positions are worse: a value dropped into an `ORDER BY` or a column list can inject a subquery, a function call, or a comment that changes the rest of the statement.

```js
// Vulnerable: input becomes part of the SQL grammar
app.get("/orders", async (req, res) => {
  const status = req.query.status ?? "open";
  const sql = `SELECT id, total FROM orders WHERE status = '${status}'`;
  res.json(await db.query(sql));
});
// GET /orders?status=open' OR '1'='1
```

The impact depends on the database account, not on the injection technique. A read-only web account can still leak every row it can select, including other tenants if row-level security is absent. A write account can modify or delete data, insert an administrator, or change a price. A broadly privileged account can read server files, execute programs, or pivot into the operating system through features such as PostgreSQL `COPY ... FROM PROGRAM` or SQL Server `xp_cmdshell`.

## Parameterized queries and prepared statements

A parameterized query keeps the SQL text and the values in separate channels. The driver sends the statement to the server for parsing, then sends the values in a separate message, often called a bind. The server compiles the statement once, with placeholders standing in for values, and substitutes the bound data at execution time. The value `x' OR '1'='1` is stored as a string that happens to contain quotes and keywords; it never becomes part of the parse tree.

A prepared statement is the server-side form of the same mechanism. It may be created explicitly with a SQL command or implicitly by the driver's protocol, but the safety property is identical: the statement shape is fixed before the data arrives. "Prepared" is not a magic word. `PREPARE stmt FROM CONCAT('SELECT * FROM users WHERE id = ', user_input)` is still concatenation, and it is still injectable.

```js
// node-postgres: $1 placeholders, values sent separately
const { rows } = await pool.query(
  "SELECT id, total FROM orders WHERE status = $1 AND tenant_id = $2",
  [status, tenantId]
);

// mysql2: ? placeholders; execute() uses server-side prepares
const [rows] = await pool.execute(
  "SELECT id, total FROM orders WHERE status = ? AND tenant_id = ?",
  [status, tenantId]
);
```

The rule to enforce in review is simple: the SQL text must be a constant in the source, or a fixed template whose only variable parts are placeholders. Anything else is a sink that needs justification.

Prepared statement caching has a tradeoff: server-side prepares avoid repeated parsing, but a cached generic plan can be slower for skewed data. PostgreSQL exposes `plan_cache_mode` to force custom or generic behavior, and transaction-level poolers complicate protocol-level prepares. Configure the binding layer; never remove it.

## Placeholders in PostgreSQL and MySQL

Both databases separate identifier positions from value positions, but their placeholder syntax and driver behavior differ. The table below is the practical map.

| Bind target | PostgreSQL | MySQL |
| --- | --- | --- |
| Literal value | `$1`, `$2` with `pool.query(text, values)` | `?` with `pool.execute(text, values)` |
| Named parameter | Not native; the driver rewrites `:name` to `$n` | Not native; the client rewrites `:name` to `?` |
| Table or column name | Not allowed; map to a fixed identifier after an allowlist check | Not allowed; map to a fixed identifier after an allowlist check |
| Sort direction | Not allowed; map `asc` and `desc` to constants | Not allowed; map `asc` and `desc` to constants |
| `LIMIT` and `OFFSET` | `LIMIT $1 OFFSET $2` | `LIMIT ? OFFSET ?` with native prepares |
| Multiple statements | Not available in the extended query protocol | Rejected by server-side prepared statements |

PostgreSQL's SQL-level `PREPARE` keeps the same `$1` numbering. You can write `PREPARE find_order (bigint) AS SELECT id, total FROM orders WHERE id = $1;`, then run `EXECUTE find_order(42);` and release it with `DEALLOCATE find_order;`. The type list is optional but makes the intended types explicit. Protocol-level prepares, which most drivers use, send the same information through Parse, Bind, and Execute messages.

MySQL uses `?` and session user variables. A typical server-side sequence is `PREPARE stmt FROM 'SELECT id FROM orders WHERE id = ?';`, `SET @id = 42;`, `EXECUTE stmt USING @id;`, and `DEALLOCATE PREPARE stmt;`. The statement name and user variables are session-scoped, so a pooled connection must clean up after itself. Two driver details matter in practice: mysql2's `query()` performs client-side escaping while `execute()` uses real prepared statements, and PDO's emulated prepares are enabled by default for MySQL, so `PDO::ATTR_EMULATE_PREPARES => false` is needed for native behavior.

Once the query is assembled, format it before review with the [SQL formatter](/tools/sql-formatter). Consistent keyword and indentation style makes a stray interpolated fragment obvious to a reviewer who is scanning dozens of queries.

## ORMs, raw fragments, and dynamic identifiers

A mature ORM binds values by default, which removes the most common bug. The risk moves to the escape hatches. Prisma's `$queryRawUnsafe` and `$executeRawUnsafe` accept arbitrary strings, while the tagged-template `$queryRaw` form parameterizes its interpolations. Sequelize binds values passed through `replacements` but not strings assembled with JavaScript interpolation. Knex's `whereRaw("id = ?", [id])` is safe, while `whereRaw("id = " + id)` is not; `orderByRaw` with user input is a common injection point. TypeORM's `.where()` accepts either a parameter object or a raw string; Django's `extra()`, ActiveRecord string conditions, and JPA native queries have the same failure mode.

The review question is not whether an ORM is used, but where a query accepts a string that contains SQL; require a binding or allowlist at every such sink.

Dynamic identifiers cannot be bound at all. A sort parameter, a filterable column, a table suffix, or a report field chosen by the user must be mapped through a server-side allowlist to a fixed fragment: map `newest` to `created_at DESC`, `oldest` to `created_at ASC`, and `total` to `total DESC`, then reject any value that is not a key in that map with a 400 before building the statement.

The object lookup is the control. Adding `req.query.sort` to a template, quoting it with backticks, or stripping "dangerous" characters all fail eventually, because the parser still receives attacker-influenced text. The same rule applies to column lists in `INSERT` and `SELECT`, to `ASC` and `DESC`, and to operators. For an `IN` list, do not join values into the SQL string; either expand placeholders to match the array length or use an array parameter such as PostgreSQL's `WHERE id = ANY($1::bigint[])`.

## Stored procedures and dynamic SQL

A stored procedure with typed parameters protects the values it receives, as long as its body uses them as values. It does not protect a procedure that assembles dynamic SQL. PostgreSQL's `EXECUTE` takes a string, so `EXECUTE 'SELECT * FROM orders WHERE id = ' || quote_literal(user_id)` is still string building; the safe pattern is `EXECUTE format('SELECT * FROM orders WHERE %I = $1', column_name) USING user_id`, or a static statement with `$1`. Use `%I` for identifiers and `%L` for literals when `format()` is unavoidable, and prefer `USING` for every value.

MySQL procedures have the same split. `PREPARE stmt FROM @sql; EXECUTE stmt USING @id;` is safe when `@sql` is a fixed template and `@id` carries the value. `SET @sql = CONCAT('SELECT * FROM orders WHERE id = ', user_id);` is concatenation with extra steps, even though it lives inside a procedure.

SQL Server shows the same split: `EXEC sp_executesql` with typed parameters binds, while `EXEC('...' + @id)` concatenates. A procedure, definer, or statement name does not change which pattern is in use.

Privilege escalation is the second stored-procedure risk. A PostgreSQL `SECURITY DEFINER` function runs with the owner's rights, so an attacker who can influence `search_path` may shadow an operator or function and execute code as the owner. Set `search_path` explicitly on the function, schema-qualify objects, and grant `EXECUTE` only to roles that need it. MySQL's `SQL SECURITY DEFINER` has the same concern: the definer should hold the minimum privileges, not administrative rights.

## Input validation is defense in depth

Validation is valuable, and it is not the fix. Checking that an ID is an integer, a status is one of five values, a name is at most 200 characters, or a JSON body matches a schema reduces the number of paths that reach the database and catches bugs early. An enum is particularly useful when the value selects a column or a sort order, because the enum becomes the allowlist.

The limit is that legitimate data and malicious data share characters. A customer named `O'Brien` requires an apostrophe in the database. A product code may contain `%` or `_`, which are wildcards inside `LIKE`. A search term may contain `--` as ordinary punctuation. Validation that rejects all quotes breaks real users; validation that strips them silently corrupts data and teaches the team to trust a sanitizer that cannot understand SQL context.

Treat validation as one layer of a stack: schema validation at the API boundary, type coercion that rejects rather than truncates, size limits on every string, allowlists for identifiers, and parameter binding for values.

Second-order injection is the case that validation alone misses. A value is stored safely through a parameterized `INSERT`, then read back and concatenated into a report query, an export job, or an admin search. The original write looked correct, and the later read is the sink. Test round-trips: store payload-like strings, then exercise every path that reads them.

## Escaping and quoting are fragile by design

Manual escaping is a context-sensitive operation disguised as a string function. It depends on the connection character set, the SQL mode, the string literal syntax, and whether the value is used as a string, an identifier, or a pattern. That is why escaping fails in ways that unit tests rarely catch.

In MySQL, `mysql_real_escape_string` is only correct for the character set of the current connection. If the application says `SET NAMES gbk` and the server interprets the bytes differently, a multibyte character can consume the backslash that was meant to escape a quote; this class of bug produced real injections. `addslashes` is not an SQL escaper at all, and the `NO_BACKSLASH_ESCAPES` SQL mode changes the rules again, so a query that is safe in one configuration is unsafe in another.

PostgreSQL has its own context switches: `standard_conforming_strings` controls whether backslashes are special in ordinary strings, `E'...'` strings have different rules, and dollar-quoted strings have another set. Doubling quotes handles a string literal and nothing else; it does not quote identifiers, and it does not neutralize `LIKE` wildcards. Server-side `quote_literal`, `quote_nullable`, and `quote_ident` beat hand-rolled replacements, but still require the right context.

Escaping belongs only in legacy code that cannot migrate to parameters because of a driver or vendor constraint. Centralize it, test it against the real connection settings, and track its removal; a parameterized query has no charset-dependent edge cases.

## Least privilege, error handling, and blast radius

Parameterization prevents the injection; least privilege limits what a successful injection can do. The application account should have `SELECT`, `INSERT`, `UPDATE`, and `DELETE` only on the schemas it uses, and nothing else. It should not own tables, run migrations, or hold `CREATE`, `ALTER`, or `DROP`. In MySQL, remove `FILE`, `PROCESS`, and `SUPER`. In PostgreSQL, remove `SUPERUSER`, `CREATEROLE`, `pg_read_server_files`, and `pg_execute_server_program` from application roles. In SQL Server, keep `xp_cmdshell` disabled and avoid broad `db_owner` membership.

Use separate accounts for migrations, reporting, and the application. A read-only replica is a better place for analytics than the primary. PostgreSQL row-level security adds a second boundary for shared tables: policies keyed on `current_setting('app.tenant_id')` block cross-tenant rows even when a query forgets a tenant filter. Review grants with `SHOW GRANTS` in MySQL and `has_table_privilege` or `information_schema.role_table_grants` in PostgreSQL.

Error handling is about information, not prevention. A verbose driver error can reveal the query text, table names, column names, and database version, which helps an attacker choose a payload. Return a stable error code and a request ID to the client, log the detail server-side, and make sure production mode does not include stack traces. In PHP, disable `display_errors`; in Django, keep `DEBUG=False`; in Node, do not serialize `error.stack` into an API response.

Hiding errors does not stop blind injection. Time-based payloads work with no output at all, and boolean-based payloads work through status codes or row counts. The reason to hide errors is to reduce the information available for the next attempt, not to substitute for binding.

## WAFs, SAST, and safe testing with harmless payloads

A web application firewall is a useful virtual patch and a poor primary control. Signature rules can be bypassed with inline comments, case changes, alternate encodings, JSON bodies, or parameter pollution, and a rule tuned for one application will miss a new query shape. A positive security model that allows known-good parameter formats is stronger than a blocklist, but it still belongs behind parameterized queries, not in front of them.

Static analysis finds concatenated SQL patterns a reviewer would miss, but produces false positives around query builders and misses flows that cross functions. Treat every finding as a sink question: is the SQL text constant, and is every value bound? Dynamic scanners such as sqlmap are valuable in an authorized test environment and dangerous everywhere else.

A safe test plan uses a disposable database with synthetic data, avoids shared staging, has explicit authorization and scope, and sends only payloads that cannot destroy data. Use one-second delays rather than long sleeps, and avoid `DROP` and `TRUNCATE`.

Harmless payloads that reveal a vulnerability without damaging anything include `'`, `''`, `' OR '1'='1`, `1' AND '1'='2`, `abc' --`, a union payload matched to the column count, and a one-second time payload such as `pg_sleep(1)` or `SLEEP(1)`. For each parameter, assert that the response has no extra rows, no measurable delay beyond the baseline, no SQL error text, and no change in status code. Then store `O'Brien`, `100%`, `_admin`, and a backslash value, and confirm they round-trip exactly.

Fixtures make these tests repeatable. The [SQL to JSON](/tools/sql-json) converter turns a small `INSERT` statement into a JSON array that a test can load, and the [JSON to SQL](/tools/json-to-sql) converter generates seed `INSERT` statements from JSON for a disposable database. Neither tool executes SQL, and neither should build runtime queries from user input; use generated statements for test data only.

## Verification checklist with pass criteria

A fix is complete only when it can be demonstrated. Use the checklist below as a release gate for any change that touches SQL, and record the evidence rather than a verbal assurance.

| Check | Pass criterion |
| --- | --- |
| Query inventory | Every SQL sink uses placeholders or a reviewed allowlist; zero unapproved interpolation |
| Identifier handling | Unknown `sort`, `column`, or `table` values return 400 before any SQL is sent |
| Payload suite | Tautology, union, comment, and one-second time payloads add no rows and no delay |
| Data round-trip | Names such as `O'Brien` and values containing `%`, `_`, and `\` survive unchanged |
| Privileges | The app account has no DDL, `FILE`, `SUPER`, or server-file rights; migrations use another account |
| Error surface | Forced failures return a generic message and request ID, with no SQL or schema names |
| Raw ORM sinks | Each unsafe raw call has binding or an allowlist plus a review note |
| Second-order paths | Reports, exports, and admin filters never concatenate stored values |
| Logs | Query logs are access-controlled, redacted where required, and retained on a defined schedule |
| Scanner results | No open high-severity SQL injection finding without an owner and an accepted-risk record |

Run the payload suite in CI against a disposable database, and review privileges and logging on a schedule; both drift independently of code. When a finding is accepted, record the compensating control, owner, and expiry date; an unowned exception is indistinguishable from an unknown vulnerability.

The end state is not a blocklist that recognizes yesterday's payloads. It is a codebase where the SQL grammar is fixed at compile time and input only ever arrives as typed data. When that property holds, a payload is just an unusual string.

## Frequently asked questions

### Are parameterized queries enough to stop SQL injection?

They are the primary control, but they only cover values. Table names, column names, sort direction, and SQL keywords cannot be bound, so those positions still need a fixed allowlist. Raw ORM fragments and dynamic SQL inside procedures must also be reviewed.

### Why can't I parameterize a table name or an ORDER BY column?

The database parses the statement before it binds values, so the parser must already know the table, column, and sort direction. A placeholder is only valid where a literal value is allowed. Map the client's choice to a constant identifier instead of building one.

### Is input validation useless for SQL injection?

No, it is useful defense in depth: type checks, length limits, and enums reduce attack surface and catch mistakes. It cannot replace binding, because legitimate data such as O'Brien contains the same characters that payloads use.

### Do prepared statements make queries slower?

Usually not. Server-side prepares save parse work on repeated statements, but plan caching can pick a generic plan that is worse for skewed data. Measure the actual workload and keep the statement text parameterized either way.

### How do I test for SQL injection without damaging data?

Use a disposable database with synthetic data, never production. Send tautology, union, comment, and one-second time payloads to every parameter, then assert that row counts, timing, and error messages do not change.

## References

- [OWASP: SQL Injection Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html)
- [PostgreSQL: PREPARE](https://www.postgresql.org/docs/current/sql-prepare.html)
- [MySQL: Prepared Statements](https://dev.mysql.com/doc/refman/8.4/en/sql-prepared-statements.html)
- [CWE-89: SQL Injection](https://cwe.mitre.org/data/definitions/89.html)

---

- Canonical: https://www.jsonmind.com/guides/sql-injection-prevention
- Locale: en
- Published: 2026-11-17
- Updated: 2026-11-17
- Tools: sql-formatter, sql-json, json-to-sql