SQL Injection
SQL injection is putting untrusted text into a query so it is executed as SQL. Parameter binding keeps data out of the SQL parser. String concatenation does not.
Detailed Explanation
The broken pattern is:
pool.query(`SELECT * FROM users WHERE email = '${email}'`);
If email is x' OR '1'='1, the filter disappears. If it is x'; DROP TABLE users;--, you hope the driver refuses multiple statements (many do not in every mode). The attacker did not need a password.
The fix is a placeholder and a values array. Postgres: $1, $2. MySQL: ?. The driver sends the SQL and the data separately. The engine never parses the data as syntax.
pool.query("SELECT * FROM users WHERE email = $1", [email]);
ORMs and query builders do this when you use their where objects. They do not when you interpolate into raw() or $queryRawUnsafe. Tagged template raw helpers (prisma.$queryRaw\... ${email}`) bind. Review every raw`.
Identifiers (table names, ORDER BY columns) cannot be bound as values in most engines. If the user picks a sort column, allowlist: const cols = { email: "email", created: "created_at" }; sql += cols[sort].
NoSQL injection exists too ({ $gt: "" } in Mongo). The rule is the same: do not turn request JSON into a query operator map unchecked.
What it costs you: a breached database. Prevention is mechanical: no user string in SQL text. Tools (linters, sql-template-strings) help. Tests that pass ' OR 1=1 as input should return zero rows, not every row.
Reach for bound parameters always. Reach for an allowlist for identifiers. Reach for least-privilege DB roles so a missed injection cannot DROP.
Second-order injection is the leftover case: you bind on insert, then later concatenate the stored value into another query (a report builder, a stored procedure argument). Treat every value as untrusted even if it came from your own table. The same rule applies to CSV import and webhook payloads.
WAF rules and sqlmap scans are extra. They do not replace binding. A review that greps for ` interpolation next to query( or raw( is cheaper than an incident.
Code Examples
Safe
// Safe
const { rows } = await pool.query(
"SELECT id FROM users WHERE email = $1 AND role = $2",
[email, role],
);
// Unsafe
// await pool.query("SELECT id FROM users WHERE email = '" + email + "'");const SORT = { email: "email", created: "created_at" };
function list(pool, sortKey) {
const col = SORT[sortKey] ?? "id";
return pool.query(`SELECT id, email FROM users ORDER BY ${col} ASC`);
}Prisma: tagged raw is bound; Unsafe is not
// Prisma: tagged raw is bound; Unsafe is not
// await prisma.$queryRaw`SELECT * FROM users WHERE email = ${email}`;Common Gotchas
Quotes around a concatenated value are not safety
attackers write quotes too. Bind.
Identifiers cannot use `$1` as a table name in normal SQL
allowlist columns and tables.
`LIKE %${q}%` is bound but still expensive and wildcard-injectable
escape `%` and `_`.