← Back to SQL, page 14

sql-0271 · Medium mid

Parameters cannot be used for table or column names. How do you safely let users choose the sort column?

Map user choices to a fixed allow-list of column names in application code, and insert only the mapped name into the SQL. Reject anything not in the list. Bind parameters still carry every value; only identifiers that come from your own list are concatenated.

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