SQL Injection (SQLi)

Difficulty: Beginner

Question

What is SQL injection, and how do you prevent it in application code?

Answer

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.

How the injection happens

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:

  • Classic / in-band: results come straight back in the response, often via UNION SELECT.
  • Error-based: database error messages leak table or column names.
  • Blind (boolean or time-based): no output, but the attacker infers data from true/false page differences or deliberate delays.
  • Second-order: malicious input is stored safely, then later used unsafely in another query.

Why parameterized queries work

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.

Defence in depth

  1. Parameterize everything, including in ORMs. Prisma, Sequelize, TypeORM, Django ORM and Hibernate are safe for normal queries, but raw escape hatches like $queryRawUnsafe, sequelize.query with string interpolation, or .extra() are not.
  2. Allowlist identifiers. Parameters cannot be used for table names, column names or ORDER BY direction. Map user choices to known values, e.g. { price: 'price', date: 'created_at' }.
  3. Least privilege. The app's DB user should not own the schema or have DROP rights. A reporting service needs only SELECT.
  4. Validate input for type and format (an orderId should be a number or UUID). This reduces attack surface but is not the main fix.
  5. Hide database errors from API responses and log them server-side.
  6. Scan with SAST tools and test with tools like sqlmap in authorised test environments.

Gotchas

  • 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.
  • Stored procedures are only safe if they do not build dynamic SQL internally with string concatenation.
String concatenation vs parameterized query. The same input behaves completely differently depending on how the query is built.
Concatenated SQLParameterized SQL
Input ' OR '1'='1' --Becomes part of the WHERE clauseTreated as a literal email string
Query parsingParsed after input is mergedParsed before values are bound
ResultReturns every userReturns no rows
Escaping neededYes, fragileNo

Code examples

Vulnerable vs safe query with node-postgres

// 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.

Prisma: safe and unsafe raw queries

// 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.

Key points

  • SQLi happens when input is concatenated into SQL and parsed as code.
  • Parameterized queries separate structure from data and are the primary fix.
  • ORMs are safe until you use raw-query escape hatches with string interpolation.
  • Table names, columns and sort direction cannot be parameters; use an allowlist.
  • Least-privilege DB users limit the damage if an injection slips through.

Common follow-up questions

  • What is blind SQL injection and how would an attacker extract data with it?
  • Why is escaping quotes not a reliable defence?
  • How would you safely build a query with a user-selected sort column?
  • What is NoSQL injection, for example in MongoDB?

Interview tips

  • Write the vulnerable query and the parameterized fix side by side; it is a coding question in disguise.
  • Mention ORM raw-query pitfalls; it shows you know frameworks are not magic.
  • Add least privilege as defence in depth, but keep parameterization as the headline answer.

Concepts covered

SQL Injection, Parameterized Queries, Prepared Statements, ORM Raw Queries, Least Privilege

More Web Security (OWASP, JWT, XSS, CSRF) questions