Difficulty: Beginner
What is SQL injection, and how do you prevent it in application code?
SQL injection (SQLi) happens when user input is concatenated into a SQL string, so the database treats part of that input as SQL code instead of data. An attacker can then read other users' rows, bypass login, modify data or sometimes drop tables. The fix is to always use parameterized queries (prepared statements), where the query structure and the values are sent separately and input can never change the query's meaning.
Consider a login query built like this: "SELECT * FROM users WHERE email = '" + email + "' AND password_hash = '" + hash + "'". If someone types ' OR '1'='1' -- as the email, the query becomes ... WHERE email = '' OR '1'='1' --' AND .... The -- comments out the rest, the OR condition is always true, and the first user (often an admin) is returned.
Common variants interviewers mention:
UNION SELECT.With a prepared statement, the database parses and plans SELECT * FROM users WHERE email = $1 first, then binds the value. Whatever is in the value, including quotes and --, is treated as a literal string. This is not the same as escaping; escaping tries to neutralise characters and is easy to get wrong across encodings and databases.
$queryRawUnsafe, sequelize.query with string interpolation, or .extra() are not.ORDER BY direction. Map user choices to known values, e.g. { price: 'price', date: 'created_at' }.DROP rights. A reporting service needs only SELECT.orderId should be a number or UUID). This reduces attack surface but is not the main fix.LIKE patterns: parameterize the value and escape % and _ if users should not use wildcards.IN (...) lists: generate one placeholder per value or use = ANY($1) in PostgreSQL with an array.| Concatenated SQL | Parameterized SQL | |
|---|---|---|
| Input ' OR '1'='1' -- | Becomes part of the WHERE clause | Treated as a literal email string |
| Query parsing | Parsed after input is merged | Parsed before values are bound |
| Result | Returns every user | Returns no rows |
| Escaping needed | Yes, fragile | No |
// VULNERABLE: input is spliced into the SQL text
const q = `SELECT id, name FROM users WHERE email = '${req.body.email}'`;
await pool.query(q);
// SAFE: placeholders, values sent separately
await pool.query(
'SELECT id, name FROM users WHERE email = $1',
[req.body.email]
);
// SAFE: dynamic sort column via allowlist (cannot be a parameter)
const SORT = { price: 'price', newest: 'created_at' };
const col = SORT[req.query.sort] ?? 'created_at';
await pool.query(
`SELECT * FROM products WHERE category_id = $1 ORDER BY ${col} DESC LIMIT 20`,
[req.query.categoryId]
);
Values go through placeholders; identifiers that cannot be parameterized are picked from a fixed map, never taken directly from input.
// Safe: tagged template, Prisma parameterizes ${email}
const users = await prisma.$queryRaw`
SELECT id FROM "User" WHERE email = ${email}`;
// Unsafe: builds a plain string, no parameterization
const bad = await prisma.$queryRawUnsafe(
`SELECT id FROM "User" WHERE email = '${email}'`
);
ORMs are safe by default, but their raw escape hatches can reintroduce SQLi if you pass interpolated strings.
SQL Injection, Parameterized Queries, Prepared Statements, ORM Raw Queries, Least Privilege