TExcelTAD
Home › Programming for Security: Python, Bash, PowerShell & C Tools › SQL: String-Built versus Parameterised Queries

SQL: String-Built versus Parameterised Queries

SQL injection is more than twenty-five years old, it is still in the OWASP Top 10 (2025: A05 Injection), and it is still found in code review every week. The cause has not changed: a query is built by gluing strings together, a value from the user becomes part of the SQL text, and the database cannot tell the developer's SQL from the attacker's. The fix has not changed either: parameterised queries, where SQL text and values travel separately. Reviewing code for this is one of the most valuable things a security engineer can do, because the pattern is easy to spot and the impact (reading or changing the whole database) is high. This lesson shows the mechanism on a database the example creates in memory, then the fixes, including the cases where parameters can't help. SQL itself is taught in SQL; the survey lesson is SQL Injection.

Definitions

  • String-built query: "SELECT … WHERE name = '" + name + "'" or an f-string; the value is pasted into the SQL text.
  • Parameterised query (prepared statement, bind variables): "SELECT … WHERE name = ?" plus the value passed separately; the database parses the SQL first and then binds the value as data, so it can never become SQL. Placeholders differ by driver: ? (sqlite3), %s (psycopg, MySQL drivers), :name, $1.
  • Identifier: a table or column name. Placeholders bind values only, never identifiers or keywords such as ASC/DESC.
  • Second-order injection: a value is stored safely, then later read back and pasted into another query.

The mechanism, on a toy database

The database lives only in this example's memory: three users with fake password hashes. The vulnerable login concatenates both fields; the attacker types a quote and a comment in the user name.

python · try it yourself
import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT UNIQUE, pw_hash TEXT, role TEXT);
INSERT INTO users (name, pw_hash, role) VALUES
  ('alice', 'h$alice-lab', 'admin'), ('bob', 'h$bob-lab', 'user'), ('carol', 'h$carol-lab', 'user');
""")

def login_unsafe(name, pw_hash):
    sql = f"SELECT name, role FROM users WHERE name = '{name}' AND pw_hash = '{pw_hash}'"
    print("  SQL:", sql)
    return db.execute(sql).fetchall()

def login_safe(name, pw_hash):
    sql = "SELECT name, role FROM users WHERE name = ? AND pw_hash = ?"
    return db.execute(sql, (name, pw_hash)).fetchall()

print("normal:", login_unsafe("bob", "h$bob-lab"))
print("wrong pw:", login_unsafe("bob", "guess"))
print("injection:", login_unsafe("alice' --", "anything"))
print("dump:", login_unsafe("x' UNION SELECT name, pw_hash FROM users --", ""))
print()
print("safe normal:", login_safe("bob", "h$bob-lab"))
print("safe injection:", login_safe("alice' --", "anything"))
print("safe dump:", login_safe("x' UNION SELECT name, pw_hash FROM users --", ""))
  SQL: SELECT name, role FROM users WHERE name = 'bob' AND pw_hash = 'h$bob-lab'
normal: [('bob', 'user')]
  SQL: SELECT name, role FROM users WHERE name = 'bob' AND pw_hash = 'guess'
wrong pw: []
  SQL: SELECT name, role FROM users WHERE name = 'alice' --' AND pw_hash = 'anything'
injection: [('alice', 'admin')]
  SQL: SELECT name, role FROM users WHERE name = 'x' UNION SELECT name, pw_hash FROM users --' AND pw_hash = ''
dump: [('alice', 'h$alice-lab'), ('bob', 'h$bob-lab'), ('carol', 'h$carol-lab')]

safe normal: [('bob', 'user')]
safe injection: []
safe dump: []

The printed SQL shows what happened. In the injection case the quote closes the string, and -- turns the password check into a comment, so the query asks only for alice: login as the administrator without a password. The UNION case appends a second query and returns every name and password hash. With placeholders the same inputs are just strange user names that match no row.

The SQL injection lab builds the same kind of login query as you type, colouring every character by where it came from and what the parser made of it (green: input kept as data, red: input that became SQL code). It starts on the comment attack: admin'-- with a wrong password returns 1 row and signs in as admin, while the parameterised query next to it returns 0 rows. Then try the tautology ' OR '1'='1 as the username with alice's password: only 1 row comes back, because AND binds tighter than OR (the lab prints the parsed WHERE with parentheses); put the tautology in the password as well and all 3 rows match.

usernameadmin'--passwordwrong-guesspassword shown in clear for the demoidusernamepasswordrole1alices3cretuser2bobhunter2user3adminK#9vT!q2adminconcatenated: "…WHERE username = '" + user + "' AND password = '" + pass + "'"SELECT id, username, role FROM users WHERE username = 'admin'--' AND password = 'wrong-guess'parsed as: WHERE username = 'admin'1 row → signed in as "admin" (admin)parameterised: the query text is fixed, the inputs are bound as valuesSELECT id, username, role FROM users WHERE username = ? AND password = ??1 = 'admin''--'?2 = 'wrong-guess'0 rows → sign-in fails: quotes, OR, -- and UNION stay characters of a valuekey: SQL from the app · input kept as data · input that became SQL code · comment

Where placeholders don't reach

Sorting and column selection are the classic gaps: ORDER BY ? binds a constant, not a column, so developers fall back to string building there. The fix is an allowlist that maps user choices to fixed SQL fragments. The second gap is LIKE, where % and _ in the value are wildcards even when bound safely.

python · try it yourself
import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, price REAL, secret_cost REAL);
INSERT INTO products (name, price, secret_cost) VALUES
  ('lab cable', 4.5, 1.1), ('lab_switch', 39.0, 21.0), ('lab router', 59.0, 30.5);
""")

SORTS = {"name": "name", "price": "price", "price_desc": "price DESC"}

def list_products(sort):
    order = SORTS.get(sort)
    if order is None:
        raise ValueError(f"unknown sort {sort!r}")
    return db.execute(f"SELECT name, price FROM products ORDER BY {order}").fetchall()

print(list_products("price_desc"))
try:
    list_products("(SELECT secret_cost FROM products)")
except ValueError as e:
    print("rejected:", e)

def search(term):
    escaped = term.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
    return db.execute("SELECT name FROM products WHERE name LIKE ? ESCAPE '\\'",
                      ("%" + escaped + "%",)).fetchall()

print("bound but unescaped '_':", db.execute("SELECT name FROM products WHERE name LIKE ?", ("lab_%",)).fetchall())
print("escaped search 'lab_':", search("lab_"))
print("escaped search '%':", search("%"))
[('lab router', 59.0), ('lab_switch', 39.0), ('lab cable', 4.5)]
rejected: unknown sort '(SELECT secret_cost FROM products)'
bound but unescaped '_': [('lab cable',), ('lab_switch',), ('lab router',)]
escaped search 'lab_': [('lab_switch',)]
escaped search '%': []

Unescaped, lab_% matches every product, because _ means "any one character". That is not injection, but it can turn a cheap search into a full table scan (a denial-of-service lever on big tables) or leak rows a prefix search was meant to hide. Escaping with an explicit ESCAPE character makes the user's _ and % literal.

How SQL injection is detected

  • Code review: any SQL text built with +, %, .format, f-strings, template literals or String.format that includes a variable. Semgrep, CodeQL (py/sql-injection, java/sql-injection) and Bandit (B608) flag the common forms.
  • Testing: a single quote in each parameter; a database error, a changed result count or a delay with SLEEP-style payloads means the input reaches SQL. In a lab, sqlmap automates this (shown in Web Application Security).
  • Logs: web logs with ', --, UNION, SELECT, OR 1=1, often URL-encoded (the regex lesson built such a detector); database logs with syntax errors from the application account; WAF alerts.

How it is fixed

  1. Parameterise every value, in every query, including INSERT, UPDATE, LIMIT and values read back from your own database (second-order).
  2. Allowlist identifiers and keywords (ORDER BY, column lists, table names) through a fixed mapping, as SORTS does.
  3. Use the ORM or query builder's parameter API, and treat its raw-SQL escape hatches (.raw(), text(), extra()) like string building.
  4. Least privilege: the application's database account can't DROP, read other schemas or run xp_cmdshell-style functions, which limits the damage of a missed spot.
  5. Generic error pages: don't return database errors to the client; they guide attackers.

Pitfalls

  • Escaping quotes by hand (name.replace("'", "''")) misses encodings, numeric contexts (WHERE id = 1 OR 1=1 has no quotes) and driver-specific rules.
  • Parameterising only the "user" fields. Headers, cookies, file names and values from other services are input too.
  • Stored procedures that build SQL inside (EXEC('SELECT … ' + @name)) are injectable even though the call from the application is parameterised.
  • Prepared statements created from a concatenated string are still concatenation: the value must go in the parameter list.

Practice

1. Rewrite cur.execute("DELETE FROM sessions WHERE user_id = %d" % uid) for psycopg.

cur.execute("DELETE FROM sessions WHERE user_id = %s", (uid,)). The %s is psycopg's placeholder (not Python string formatting) and the value goes in the tuple.

2. A page sorts by ?sort=price and passes it into ORDER BY. Why can't a placeholder fix it, and what can?

ORDER BY ? would bind a constant string, sorting every row by the same value. Map the parameter through an allowlist ({"price": "price", "name": "name"}) and reject anything else, as list_products does.

3. What does the injection in login_unsafe("alice' --", …) look like in a web server log, if the name was sent in a POST body?

Usually nothing: access logs record the URL, not POST bodies. That is why detection also needs application logs (failed and successful logins with the user name as given, safely escaped) or a WAF that inspects bodies.

Test yourself

Why can't a parameterised value become SQL?

  1. The driver deletes quotes
  2. The database parses the SQL text first and binds the value afterwards as data
  3. Parameters are encrypted
  4. Values are always numbers

In the example, what did -- do in the injected user name?

  1. Subtracted two numbers
  2. Started a comment, removing the password check from the query
  3. Closed the string
  4. Nothing

How do you safely make the sort column user-selectable?

  1. ORDER BY ? with a parameter
  2. Map the choice through an allowlist of fixed SQL fragments
  3. Escape quotes in the column name
  4. Use LIKE

With a bound parameter, the search lab_% matched every product. Why?

  1. SQL injection
  2. _ and % are LIKE wildcards inside the value
  3. The parameter was ignored
  4. SQLite ignores case

In the SQL injection lab, the username ' OR '1'='1 with alice's correct password returns only 1 row. Why not all 3?

  1. The parameterised query ran instead
  2. AND binds tighter than OR, so the WHERE is username = '' OR ('1'='1' AND password = 's3cret'), which only alice's row satisfies
  3. The database stops after one row
  4. The quote was escaped