# Parameterized Queries & SQL Injection

> See how pasting user input into SQL lets it become code, and how parameterized queries keep data and commands apart.

Subject: SQL | Lesson 42 of 44 | 7 min read
Interactive lesson: https://codewithanimation.in/sql/parameterized-queries-and-sql-injection
Previous: [EXPLAIN & Query Plans](https://codewithanimation.in/sql/explain-and-query-plans.md) | Next: [Connection Pooling](https://codewithanimation.in/sql/connection-pooling.md)

## When data becomes code

**SQL injection** happens when a program builds a query by gluing user input into the SQL text. Characters in the input, such as a quote or a semicolon, are then read as part of the SQL, so the user can change what the query does.

A **parameterized query** keeps the two apart. The program sends the query text with placeholders (`$1`, `$2`), and sends the values separately. The database never reads a value as SQL.

## One quote can ruin a database

Any search box, login form or URL that reaches a query is a way in. Injection can leak other users' data, change or delete rows, or drop whole tables. It is one of the oldest and most common web security problems, and the fix is simple and cheap.

## Same input, two ways

```js
// Dangerous: the input becomes part of the SQL text
db.query("SELECT id, name, email FROM users WHERE name = '" + input + "'");

// Safe: the text and the value travel apart
db.query("SELECT id, name, email FROM users WHERE name = $1", [input]);
```

Type `' OR '1'='1` in the glued version and the query becomes `... WHERE name = '' OR '1'='1'`. The test `'1'='1'` is always true, so every user comes back. Type `'; DROP TABLE users; --` and the first statement ends early, a second statement drops the table, and `--` comments out the leftover quote.

PostgreSQL's simple query protocol runs several statements in one string, as one transaction. In the parameterized version the same input is just a name nobody has, so the query returns no rows and nothing changes. The extended query protocol also takes only one statement per query text, so a second statement cannot be smuggled in.

## Common mistake: Not only attackers, and not everything can be a parameter

A harmless name like `O'Brien` breaks the glued query with `syntax error at or near "Brien"`. Gluing is a bug for honest users too. Parameters also handle quotes, dates and numbers correctly without you escaping anything. The OWASP guide says not to try to escape input by hand, because the rules differ between systems and it is easy to miss a case.

A parameter stands for a **value**. It cannot be a table name, a column name or a sort direction. If a user picks `ORDER BY name` or `ORDER BY email`, map their choice to a fixed word from a list that you wrote, and reject anything else (an allow-list).

Calling a stored procedure with parameters is safe only if the procedure itself does not build SQL by gluing text. Dynamic SQL inside it needs the same care.

Parameterizing is the main defence, not the only one. Give the application's database account only the rights it needs, so that even a mistake cannot drop a table.

## Tip: Never put a variable inside a SQL string

If a value comes from outside, whether from a form, a URL or another service, send it as a parameter. Use the placeholders your database driver gives you. As a bonus, a prepared statement lets PostgreSQL read and analyse the text once and run it many times with different values.

## Try it: Try the attacks, then the fix

Run each input with Glue into the text, and then with Send as a parameter. Watch the highlighted characters, which came from the user, and the list of tables.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/sql/parameterized-queries-and-sql-injection

## Check yourself

### Question 1

A program glues the input `' OR '1'='1` into `WHERE name = '...'`. What does the query return?

- A. Every user, because '1'='1' is always true
- B. No rows, because no user has that name
- C. An error

Correct answer: A

The input closed the string and added a condition that is always true, so the WHERE filters nothing.

- Why not B: That is what a parameterized query does. When the text is glued in, the quote ends the string and OR '1'='1' becomes part of the condition.
- Why not C: The quotes balance, so it is valid SQL. That is why it is so dangerous.

### Question 2

Why does a parameterized query stop `'; DROP TABLE users; --` from dropping the table?

- A. The value is sent separately and is only ever compared as text, never read as SQL
- B. PostgreSQL deletes the dangerous words from the value
- C. DROP TABLE is not allowed inside a SELECT

Correct answer: A

The query text is fixed first. The value arrives apart from it, so it can only be a value in a comparison.

- Why not B: Nothing is filtered or changed. The value is used exactly as it is, as data.
- Why not C: The glued version does run the DROP, as a second statement. The difference is that a parameter is never parsed as a statement.

### Question 3

A page lets the user choose how to sort: name or email. Can you pass the column name as a parameter, `ORDER BY $1`?

- A. No. Parameters are values. Map the choice to a fixed column name from an allow-list
- B. Yes, parameters work anywhere in the query
- C. Yes, if you escape the quotes first

Correct answer: A

Use an allow-list: if the choice is 'email', write ORDER BY email yourself, and reject any other choice.

- Why not B: A parameter takes the place of a value, not of a table or column name, or a sort direction.
- Why not C: Manual escaping is discouraged, and an identifier is not a quoted value anyway.

## Remember this

- SQL injection is user input that becomes part of the SQL text. A quote and a semicolon can start a new statement.
- A parameterized query sends the text and the values apart, so a value is never read as SQL.
- Parameters are values only. For table names, column names and sort order, use an allow-list.
- Do not escape by hand. Also use a database account with only the rights it needs.
