download

WHERE uses ? placeholders. Why is ORDER BY still SQL-injectable?

Security~10 minReviewed 3 Dec 2026Free · No sign-in

Question

An orders API binds WHERE tenant_id = ? properly, then interpolates ORDER BY {sort} {direction} because SQLite does not bind column names or ASC/DESC. A tester passes sort = "CASE WHEN (SELECT substr(pin,1,1) FROM admin_secrets)='9' THEN cents ELSE -cents END" and extracts an admin PIN from the row order.

  1. Why do ? placeholders fail for dynamic columns and sort direction?
  2. Fix list_orders(con, tenant_id, sort, direction) using strict allowlist dictionaries for both sort and direction.
  3. Why is stripping spaces or quotes from sort still risky?
"CODE · PYTHON"
def list_orders(con, tenant_id, sort="created_at", direction="asc"):
    sql = (f"SELECT id, cents FROM orders WHERE tenant_id = ? "
           f"ORDER BY {sort} {direction}")
    return con.execute(sql, (tenant_id,)).fetchall()
Show hints (3)
  1. "VALUES VERSUS IDENTIFIERS"

    Placeholders (?) only represent SQL data values. A query planner compiles table names, column identifiers, and keywords like ASC/DESC before binding parameters.

  2. "MAP FIXED TOKENS"

    Map user keys like "date" and "total" through ALLOWED_SORT and ALLOWED_DIR dictionaries so only server-authored SQL tokens ever reach the query string.

  3. "BLIND SORT ORACLE"

    Even without spaces or quotes, SQLite accepts /**/ comments, char(), and unexposed column names like password_hash inside ORDER BY.

Show checked explanation

SQL placeholders (?) bind only data values, never column names, table names, or ASC/DESC keywords. Interpolating sort lets an attacker inject a CASE WHEN expression into ORDER BY to exfiltrate other tables via row order. Map user inputs through strict allowlist dictionaries (ALLOWED_SORT, ALLOWED_DIR) and reject unknown keys before running SQL.

"SOLUTION · PYTHON"
import sqlite3

ALLOWED_SORT = {"date": "created_at", "total": "cents"}
ALLOWED_DIR = {"asc": "ASC", "desc": "DESC"}

def list_orders(con, tenant_id, sort="date", direction="asc"):
    col = ALLOWED_SORT.get(sort)
    order = ALLOWED_DIR.get(direction.lower())
    if col is None or order is None:
        raise ValueError("invalid sort option")
    sql = (f"SELECT id, cents FROM orders WHERE tenant_id = ? "
           f"ORDER BY {col} {order}, id ASC")
    return con.execute(sql, (tenant_id,)).fetchall()

con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE orders(id, tenant_id, created_at, cents)")
con.executemany("INSERT INTO orders VALUES (?, ?, ?, ?)",
                [(1, 1, "2026-11-02", 100), (2, 1, "2026-11-01", 500)])
print("date:", list_orders(con, 1, "date", "asc"))
print("total:", list_orders(con, 1, "total", "asc"))
"OUTPUT"
date: [(2, 500), (1, 100)]
total: [(1, 100), (2, 500)]

Author-checked on SQLite 3.49.1 and CPython 3.12.10 against synthetic in-memory orders and admin_secrets tables, reproducing full 4-digit boolean-blind PIN extraction and verifying the allowlist fix; official OWASP, SQLite, and Python sqlite3 links checked. Checked by an editor other than the author.

Walkthrough

Parameterized queries keep WHERE tenant_id = ? safe because SQLite parses the SQL structure first and binds tenant_id as a literal value afterward. That same rule means ? cannot select a column or keyword. Writing ORDER BY ? in SQLite sorts every row by the same constant text 'cents', turning sorting into a silent no-op, while ORDER BY cents ? is a syntax error.

Interpolating sort straight into ORDER BY hands the attacker a full SQL expression slot. On our two orders (1, 100) and (2, 500) with admin_secrets.pin = '9421', injecting CASE WHEN (SELECT substr(pin,1,1) FROM admin_secrets)='9' THEN cents ELSE -cents END leaks the PIN one character at a time:

sort inputstarter resultfixed list_orders
"date" (created_at)[(2, 500), (1, 100)][(2, 500), (1, 100)]
"total" (cents)[(1, 100), (2, 500)][(1, 100), (2, 500)]
CASE WHEN ...='9' ... (true)[(1, 100), (2, 500)] (leaks '9')Raises ValueError
CASE WHEN ...='0' ... (false)[(2, 500), (1, 100)] (false branch)Raises ValueError

Map public keys to server-owned SQL tokens. Notice the caller passes API labels ("date", "total", "asc", "desc"), never raw schema names. ALLOWED_SORT and ALLOWED_DIR translate those keys into fixed strings written in your source code. Unknown keys fail closed with ValueError (HTTP 400 or 422), and , id ASC keeps pagination ties deterministic.

Why sanitizing sort with regexes fails. Blocking spaces is bypassed with CASE/**/WHEN.... Blocking quotes is bypassed with char(57). Even allowing only [a-z_]+ lets a caller sort by hidden sensitive columns on the same table (such as internal_score or email) or trigger unindexed full-table sorts.

Common mistakes

  • Replacing ORDER BY {sort} with ORDER BY ?. In SQLite, ORDER BY ? binds a constant string, so every row gets the same sort key and sorting silently breaks.
  • Stripping spaces, semicolons, or quotes from sort. Attackers use /**/ comments, numeric comparisons, or char() inside CASE WHEN with zero spaces or quotes.
  • Allowing any [a-z_]+ string as a column name. Callers can still probe hidden columns on the table or sort on unindexed text blobs to cause DoS.
  • Allowlisting sort while leaving direction interpolated. Attackers can still inject expressions right after a valid column name via direction.

Follow-up questions

  • "How do you safely handle dynamic multi-column sorting like sort=date:desc,total:asc?" Split the input into a bounded list, such as at most 3 sort keys, and validate every (key, dir) pair against ALLOWED_SORT and ALLOWED_DIR. Reject unknown or duplicate keys, then join only the mapped server strings with ", ".
  • "If you double-quote a user column name with "..." or psycopg.sql.Identifier, does that replace an allowlist?" Quoting stops syntax injection, yet it is still weaker than an allowlist. A caller could name hidden internal columns, unindexed columns that slow queries, or expose schema errors. Keep an explicit allowlist of API-exposed columns.
  • "How does this relate to parameterized WHERE clauses and IN (...) lists?" Values in WHERE and IN lists always use placeholders (?, one per element in IN (?, ?, ?)). Only structural SQL pieces that cannot be parameterized (identifiers, ASC/DESC, operators) use strict allowlist maps.

What a strong answer covers

Explains why ? binds values rather than identifiers and demonstrates boolean-blind CASE WHEN extraction via ORDER BY. Maps both column and direction through strict allowlists, and explains why regex filters and ORDER BY ? fail.

Open in interactive practice deck →

Original OfferVibe question. OWASP SQL Injection Prevention Cheat Sheet · SQLite ORDER BY · Python sqlite3 Placeholders.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.