Skip to the solution
EasyDSA13 min read

What is SQL injection and how do parameterized queries prevent it?

374 views

The problem

Question presented to candidate: "Our login page builds its query by gluing the username from the form into a SQL string. A security review flagged it as SQL injection. What does that mean, why is it dangerous, and how do parameterized queries fix it?"

What a strong answer should cover:

  • Definition: untrusted input is pasted into the SQL text, so the parser reads part of the input as SQL instead of as a value
  • Why escaping by hand is fragile, and why a bound parameter is different: the SQL text and the values travel separately, so a value can never change the shape of the query
  • Where parameters cannot help: table names, column names, ORDER BY direction and keywords cannot be placeholders, so they need an allowlist (or quote_ident / format('%I') in PostgreSQL)
  • Defence in depth: least-privilege database roles, ORM raw-query APIs used safely (for example Prisma $queryRaw tagged template vs $queryRawUnsafe), input validation as a second layer, not the fix
  • Second-order injection: data stored safely can still be unsafe later if another piece of code concatenates it into dynamic SQL

Code / implementation expected: Yes β€” show a concatenated query going wrong and the same lookup written with a placeholder.

Schema used by the examples:

  • security
  • injection

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

13 min read Β· 11 sections

Run the code

Edit the query and run it against the tables for this question.

SQLWhat string concatenation builds: normal input vs input containing a quote
SQLThe concatenated query the database actually receives: the WHERE clause is now always true
SQLThe same input treated as one value (what a bound parameter does): no user has that name
PostgreSQL: PREPARE / EXECUTE binds the value server-side, so a quote in a real name just works
PREPARE find_user(text) AS
  SELECT id, username FROM users WHERE username = $1;
EXECUTE find_user('o''brien');

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 12 of 82 in SQL

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All SQL questions
Up nextEasy

What do COALESCE and NULLIF do?

Continue