SQL Injection & Parameterized Queries
How SQL injection happens, why parameterized queries separate code from data, ORM raw-query escape hatches, and least-privilege database users.
TL;DR
SQL injection (SQLi) happens when untrusted input is concatenated into a SQL string, letting data rewrite the query's logic. Always use parameterized queries (prepared statements), use strict allowlists for dynamic table/column identifiers, avoid unsafe ORM raw-query escape hatches, and run the app with a least-privilege DB role.
Intent
Understand why string-built SQL lets attackers rewrite query ASTs, how bound parameters eliminate that class of bug, and where ORMs still have sharp edges.
Problem
Concatenating user input into a SQL string mixes code and data in the same channel. Even with an ORM, developers reach for raw SQL for complex reports or dynamic sorting (ORDER BY ${sortCol})—and one unvalidated template literal reopens the entire database to extraction or tampering.
Solution
Keep SQL structure and untrusted data strictly separated:
- Parameterized queries (prepared statements): Use
$1/?placeholders (or ORM tagged templates like Prisma$queryRaw\...``). The DB parser compiles the query plan before seeing the parameter bytes. - Allowlist identifiers: SQL parameters only work for values, not column names, table names, or
ASC/DESC. Map those through a fixedRecord<string, string>allowlist. - Least-privilege DB credentials: The web app's DB role should never be
SUPERUSERordb_owner—restrict it to the required schema and DML operations.
Real-world analogy
▶ Flow: watch it work
SQL Injection: String Concat vs Parameterized Query
Press Start or tap any step dot to trace the path.
▸All steps (4)
Code
Compare unsafe string interpolation and dynamic ORDER BY against parameterized queries and an explicit allowlist:
// UNSAFE: string interpolation in raw SQL and unvalidated ORDER BY column
const unsafeUsers = await db.query(
`SELECT id, email FROM users WHERE email = '${email}' ORDER BY ${sortBy}`,
);
// SAFE: parameterized value ($1) + strict allowlist for column identifier (ASVS V1)
const ALLOWED_SORT = {
created_at: 'created_at',
email: 'email',
} as const;
const safeSort = ALLOWED_SORT[sortBy as keyof typeof ALLOWED_SORT] ?? 'created_at';
const safeUsers = await db.query(
`SELECT id, email FROM users WHERE email = $1 ORDER BY ${safeSort} ASC`,
[email],
);When to use / when to avoid
- Use parameterized queries ($1, ?) or ORM query builders for every SQL value.
- Use a strict server-side allowlist map whenever column names, table names, or sort directions are dynamic.
- Run the application with a dedicated DB role that has only the permissions it needs.
- Never try to "fix" SQLi by stripping quotes or keywords with regexes—use prepared statements.
- Never pass interpolated strings into ORM escape hatches ($queryRawUnsafe, sequelize.literal, raw()).
How to implement
Ban raw string concatenation
Enable lint rules or SAST checks flagging template literals inside db.query or $queryRawUnsafe.
Allowlist dynamic identifiers
Map user-supplied sort or filter keys through a const object or Map before building ORDER BY.
Restrict DB role privileges
Separate migration credentials (DDL) from runtime app credentials (DML only).
Pros / Cons
- Parameterized queries eliminate SQL injection on values completely and let the DB cache query plans.
- Least-privilege DB roles limit blast radius if another vulnerability occurs.
- Identifiers (table/column names) cannot be bound as parameters and still require allowlists.
- Legacy stored procedures that concatenate dynamic SQL internally are still vulnerable.
Relations
Check yourself
Check Yourself
1. You use an ORM for normal CRUD, but write one reporting endpoint with db.$queryRawUnsafe(`SELECT ... ORDER BY ${req.query.sort}`). Is it safe?
2. Why can't you pass a column name as a $1 bound parameter in SELECT * FROM users ORDER BY $1?
Sources
Related Notes
XSS & Content Security Policy (CSP)
Reflected, stored, and DOM XSS, context-aware output encoding, React's default escaping vs escape hatches, and CSP with nonces and strict-dynamic.
CSRF & SSRF Defenses
How Cross-Site Request Forgery (CSRF) and Server-Side Request Forgery (SSRF) work, and how SameSite cookies, anti-CSRF tokens, allowlists, and metadata blocks stop them.