Full answer
Placeholders stand for values, so ORDER BY ? sorts by a constant string, not a column. Developers then reach for concatenation, which reopens injection.
An allow-list keeps control in code:
text
SORTS = {"name": "name", "newest": "created DESC", "price": "unit_price"}
order_by = SORTS.get(request_sort, "name")
sql = f"SELECT id, name FROM products ORDER BY {order_by} LIMIT ?"
cursor.execute(sql, (page_size,))The same applies to the sort direction (ASC/DESC from a two-item list), table names in multi-tenant setups, and dynamic filters, where each optional condition is a fixed SQL fragment with its own parameter.
In PostgreSQL functions that build SQL, format('%I', name) quotes identifiers and %L quotes literals, and EXECUTE ... USING binds values. Quoting identifiers prevents breaking out of the name, but an allow-list also prevents sorting by columns users should not see.
Key points
- Placeholders bind values, not identifiers
- Use an allow-list for column and direction choices
- Bind every value as a parameter
- PostgreSQL format('%I') quotes identifiers in dynamic SQL
Common mistakes
- Concatenating a sort column from the query string
- Binding ORDER BY ? and wondering why the sort does nothing
Follow-ups
- How would you build optional filters safely?
- How do you test for injection?
Tips
- Show the allow-list mapping