download

How do you pass user input to SQL safely from Python?

Python~10 minReviewed 29 Oct 2026Free · No sign-in

Question

A parts catalog in SQLite has this table:

idlabel
11maker's kit
12seal

Write find_parts(con, label) with Python's built-in sqlite3 module. It returns the ids of parts whose label equals the user's text exactly. It must work for maker's kit, which contains an apostrophe. For the text ' OR 1=1 -- it must return an empty list, because no part has that label.

"CODE · PYTHON"
import sqlite3


def find_parts(con, label):
    """Return the ids of parts whose label equals `label`."""
    ...
Show hints (2)
  1. "KEEP THEM APART"

    Don't paste the user's text into the SQL string. sqlite3 can send the SQL and the values separately. Which symbol marks the place for a value?

  2. "THE SECOND ARGUMENT"

    Write WHERE label = ? and pass the value as the second argument of con.execute. It must be a sequence, so one value needs a one-item tuple: (label,).

Show checked explanation

Use a parameterized query. Put ? in the SQL and pass the values separately: con.execute("SELECT id FROM part WHERE label = ?", (label,)). The value never becomes part of the SQL text, so it can't change the query. Placeholders work only for values, not for column names or sort order.

"SOLUTION · PYTHON"
import sqlite3


def find_parts(con, label):
    rows = con.execute(
        "SELECT id FROM part WHERE label = ? ORDER BY id",
        (label,),
    ).fetchall()
    return [row[0] for row in rows]


con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE part (id INTEGER, label TEXT)")
con.executemany("INSERT INTO part VALUES (?, ?)",
                [(11, "maker's kit"), (12, "seal")])

for text in ["maker's kit", "seal", "bolt", "' OR 1=1 --"]:
    print(text, "->", find_parts(con, text))
con.close()
"OUTPUT"
maker's kit -> [11]
seal -> [12]
bolt -> []
' OR 1=1 -- -> []

Code run on CPython 3.12 with an in-memory SQLite database against the examples above. Checked by an editor other than the author.

Walkthrough

A parameterized query has two parts: SQL text with ? marks, and a separate tuple of values. SQLite parses the SQL first. After that, each value is attached to its ?. So a value can never be read as SQL. Here the user's text can only be compared with the labels.

Compare this with pasting the text into the SQL with an f-string:

inputf-string? placeholder
maker's kitsyntax error[11]
' OR 1=1 --[11, 12][]

In the f-string version, the apostrophe in maker's kit ends the SQL string early, so the query breaks. The second input is worse. The SQL becomes WHERE label = '' OR 1=1 --'. 1=1 is true for every row, and -- turns the rest of the line into a comment. That is SQL injection: the user's text changed what the query does.

With ?, the same text is just a label that no part has. The empty list is the correct answer, not an error.

Placeholders can only stand for values. You can't bind a table name, a column name or the words ASC and DESC. ORDER BY id ? is a syntax error. For those parts of a query, choose between fixed pieces of SQL that you wrote yourself.

Common mistakes

  • Building the SQL with an f-string, % formatting or +, as in f"... WHERE label = '{label}'". An apostrophe breaks the query, and ' OR 1=1 -- returns every row.
  • Writing (label) instead of (label,). Without the comma it's a plain string, and sqlite3 treats each character as a value. "seal" gives 4 values for 1 ? and raises ProgrammingError. A one-letter label still works, so tests can miss it.
  • Binding a column name. SELECT ? FROM part with "label" returns the text 'label' once per row, not the contents of the column.
  • Forgetting that a bound % is still a wildcard in LIKE. label LIKE ? with "%" matches every row. Use = for exact matches, or escape % and _ with ESCAPE.

Follow-up questions

  • "Users can sort by id, ascending or descending. How do you add that?" Don't bind it. In SQLite, ORDER BY ? runs, but every row gets the same sort value, so the user's choice changes nothing. Map the choice to SQL you wrote yourself: {"asc": "ORDER BY id ASC", "desc": "ORDER BY id DESC"}. Reject any other key before the query runs. This is called an allow-list. Values in WHERE still use ?.
  • "Does a parameterized query make the search secure?" It stops the input from changing the SQL. That is all it does. It doesn't decide who may read which rows, and it doesn't stop a very slow, expensive query. You still need access control and limits.
  • "Does the same code work with PostgreSQL or MySQL drivers?" Not always. The idea is the same, but the placeholder mark depends on the driver. Drivers that follow Python's DB-API (PEP 249) name their style in paramstyle. sqlite3.paramstyle is 'qmark', which means ?. Other drivers may use %s or :name. With %s, still pass the values as the second argument. Never fill them in with Python's % operator.

What a strong answer covers

Uses ? with a one-item tuple and explains why string formatting allows injection. Knows the limits: column names and sort order need an allow-list, LIKE still treats % as a wildcard, and binding doesn't replace access control.

Open in interactive practice deck →

Original OfferVibe question. Topic idea from The Python Interview Handbook (Nezir Zahirovic, 2023); text, examples and code are our own.
© 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.