SQL Injection and Parameterized Queries

SQL injection occurs when untrusted input is interpreted as part of SQL syntax. Use parameterized queries through your database driver or ORM so values are transmitted separately from the SQL statement. Do not build queries by concatenating user-supplied strings. Parameters generally represent values, not arbitrary identifiers such as table names or sort directions; dynamic identifiers must be selected from an allowlist and safely quoted using appropriate library support.

An ORM does not automatically make every query safe if raw SQL is assembled unsafely. Review raw query paths and ensure values are bound as parameters.

Parameterized query with node-postgres
const result = await pool.query(
  "SELECT id, name FROM customers WHERE email = $1",
  [email]
);
💡 The $1 placeholder is bound to the email value separately from the SQL text. This example uses node-postgres; other drivers have their own parameter placeholder conventions.
Key Takeaways
  • Bind values as parameters instead of concatenating them.
  • Dynamic identifiers need allowlisting and safe identifier handling.
  • Raw SQL in an ORM still requires safe construction.
Knowledge Check

What is the primary defense against SQL injection for query values?