Skip to content

Web security basics · Part 2 of 10

SQL injection and parameterised queries

SQL injection happens when user input is glued into a query. Parameterised queries keep data and code separate and remove the whole class of bug.

· 2 min read

securitysql

SQL injection is old, well understood and still common. It happens when untrusted input becomes part of the SQL text, so the input can change what the query does.

The vulnerable pattern

Imagine a query built by concatenation:

Python
def find_user_unsafe(name):
    return "SELECT * FROM users WHERE name = '" + name + "'"

print(find_user_unsafe("x' OR '1'='1"))

The result is SELECT * FROM users WHERE name = 'x' OR '1'='1', which returns every user. With more effort an attacker can read other tables or change data.

The fix: parameters

A parameterised query sends the SQL text and the values separately. The database treats the value strictly as data, whatever characters it contains.

Python
import sqlite3

conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE users (id integer, name text)")
conn.execute("INSERT INTO users VALUES (1, 'ada')")

name = "x' OR '1'='1"
rows = conn.execute("SELECT * FROM users WHERE name = ?", (name,)).fetchall()
print(rows)   # [] - the quote characters are just part of the value

Every mainstream language and ORM supports parameters. Use them for every value, including ones that look safe.

Things parameters cannot do

Placeholders work for values, not for table names, column names or sort directions. For those, choose from a fixed allow-list in your code.

SQL
-- Parameters can fill values like this:
SELECT id, name FROM users WHERE name = $1 ORDER BY created_at DESC LIMIT $2;

Defence in depth

  1. Least privilege: the application's database account should not own the schema or be able to drop tables.
  2. Validate input for type and length. It is not a replacement for parameters, but it reduces the surface.
  3. Hide detailed errors from users, since database messages help attackers.
  4. Review ORM escape hatches: raw SQL fragments in ORMs are injection points when built from input.
  5. Test: scanners and code review should look for string-built queries.

Takeaway

Never build SQL by joining strings with user input. Use parameters for values, allow-lists for identifiers and a database account that can do only what the application needs.

A knowledge article, drafted with AI assistance and checked with automated tests. It is general background, not a description of my own experience or of any client's work.

Comments

Leave a comment

No account or email needed. Comments appear after review. A one-way hash of your IP address is kept for 30 days to fight spam, then erased.