Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 154/ 160
08. Transactions, Security & Production SQL Administration

Preventing SQL Injection (Parameterized Queries & Prepared Statements)

Stop injection with bound parameters and prepared statements-never string concat.

BeginnerParams · Prepared · Safety3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Never glue user text into SQL. Send the SQL and the user's values separately, so the values can only ever be values.

Think of it like…

Giving a bank clerk a form where you write the amount in a box, versus handing them a note they read out as instructions. Someone can write "…and also transfer everything to me" on a note; on a form, that text is just a strange amount that gets rejected.

Where you’ve seen it

A login query built as "SELECT * FROM users WHERE email = '" + email + "'" lets an attacker type ' OR '1'='1' -- and log in as the first user. db.query('SELECT * FROM users WHERE email = $1', [email]) treats the whole input as one email string.

Words you’ll hear

Parameter / placeholder
A slot in the SQL ($1, ?, %s, :name) filled with a value by the driver.
Prepared statement
SQL parsed once by the database, then executed with different parameter values.
Identifier
A table or column name. It can't be a parameter, so it must come from an allow-list.
Least privilege
Giving the app's database user only the permissions it needs, to limit damage.

Visual diagram

Loading interactive diagram

Theory & example queries

How injection works

When input is concatenated into a query, the database receives one string and parses all of it as SQL. A quote in the input closes the string literal early, and whatever follows becomes SQL: an OR '1'='1' that matches every row, a UNION SELECT that reads other tables, or a comment (--) that cuts off the rest of the query.

Escaping quotes by hand is fragile: different databases, encodings and contexts (strings, numbers, LIKE patterns) need different rules, and one forgotten call is enough. Input validation helps, but it isn't a substitute, because "valid" input like O'Brien still contains a quote.

The vulnerable pattern

query = "SELECT * FROM orders WHERE id = " + req.query.id with id = 1; DROP TABLE orders turns one lookup into two statements on drivers that allow multiple statements.

Key takeaway: Concatenated input is parsed as SQL; that's the whole vulnerability.

Parameters everywhere, allow-lists where they can't go

With parameters, the SQL is sent with placeholders and the values travel separately, so the database knows they're data. Every mainstream driver supports it: $1 in node-postgres, %s with a separate tuple in Python's psycopg, ? in JDBC and MySQL drivers. ORMs parameterize by default, but their raw-SQL helpers are vulnerable when you interpolate into them.

Placeholders only work for values. Table names, column names and ASC/DESC can't be parameters, so map user choices to a fixed allow-list ({ newest: 'created_at DESC', price: 'price ASC' }) and never insert the raw input. LIKE patterns are values too: build the pattern in code and pass it as a parameter. Finally, run the app as a database user that can't drop tables or read unrelated schemas.

Safe versions

Node: db.query('SELECT * FROM users WHERE email = $1', [email]). Python: cur.execute('SELECT * FROM users WHERE email = %s', (email,)). Note the separate argument, not an f-string.

Key takeaway: Bind every value; allow-list every identifier.
Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Review

Find every query built from input

Search the code for SQL built with +, template strings, f-strings or format() that include request data.

SQL at this step
1"… WHERE id = " + req.params.id
What to watch at this step
Red flag
string building
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

SQL injection happens when user input is pasted into SQL text, so input like ' OR '1'='1 changes the query's logic instead of being treated as data. The fix is parameterized queries (prepared statements): the SQL text and the values are sent separately, and the database never parses the values as SQL.

Why it matters: Injection still regularly leads to stolen and deleted data, and it comes from one habit: building queries with string concatenation or interpolation. Every backend interview expects you to explain it and the fix, and code reviewers look for it constantly.

When to reach for it

  • Every query that includes user input, including internal admin tools
  • Search and filter endpoints with dynamic sorting
  • Code review checklists

When to avoid or be careful

  • String concatenation or interpolation to build SQL
  • Interpolating into an ORM's raw-query helper
  • Running the application as a database superuser

Defences against SQL injection

Parameterized queries / prepared statements
Best for: Every value that comes from outside the code

Strengths: Eliminates injection for values; works in every driver.

Watch out: Can't be used for identifiers like table or column names.

Allow-listing
Best for: Dynamic identifiers: sort columns, directions, table choices

Strengths: Only known-safe strings ever reach the SQL.

Watch out: The list has to be maintained.

Escaping and input validation
Best for: A secondary check, never the main defence

Strengths: Catches obviously bad input early.

Watch out: Fragile and easy to get wrong in one place.

Interview signals & numbers to know

When this topic comes up

  • “What is SQL injection and how do you prevent it?”
  • ' OR '1'='1
  • Dynamic ORDER BY from a query parameter
  • Raw SQL in an ORM codebase
  • Security review

Benchmarks & rules of thumb

1 -
forgotten concatenation is enough to be vulnerable
$1 / ? / %s -
common placeholder styles
0 -
identifiers that can be passed as parameters

Common mistakes & follow-ups

Common interview mistakes

  • Using an f-string or template literal inside cursor.execute() or db.query(), which looks parameterized but isn't.
  • Passing a user-supplied column name straight into ORDER BY.
  • Relying on escaping quotes or front-end validation instead of parameters.

Likely interviewer follow-ups

  • How do prepared statements prevent SQL injection?
  • How do you safely let users choose the sort column?
  • Is an ORM automatically safe from SQL injection?
Interview tip: Show the attack in one line (' OR '1'='1), then the parameterized fix in your usual language, then mention identifiers and least privilege. That's a complete, senior-sounding answer.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Preventing SQL Injection (Parameterized Queries & Prepared Statements) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Row-Level Security (RLS) Policies for Multi-Tenant Databases
Next topic
Data Masking, Encryption & Protecting PII in SQL Databases