SQL injection is one of the classic security flaws that interviewers love to test. It shows whether you understand how data moves from a user’s browser to a database and whether you can think about defensive layers.

What is SQL injection in one sentence?

SQL injection is a technique where an attacker injects malicious SQL code through user‑controlled input, causing the database to execute unintended commands.

How the vulnerability works

  1. User input reaches the server – A web form, URL parameter, or API field supplies a string.
  2. The app builds a query by concatenation – The code stitches the raw string into a SQL statement.
  3. The database parses the whole string – Because the injected part isn’t escaped, the database treats it as part of the query.
  4. Unintended statements run – This can range from data leakage to full control of the DB.

The core problem is a trust boundary that isn’t enforced: the application trusts the input enough to embed it directly in the query.

Trade‑offs and why it still matters

AspectTypical trade‑offWhy it matters
PerformanceUsing prepared statements adds a tiny overhead for statement preparation.The overhead is negligible compared to the risk of a breach.
Developer convenienceString interpolation is quick and readable.Convenience invites shortcuts; security‑first code is slightly more verbose but safer.
Legacy codeOlder codebases often lack ORM layers.Refactoring legacy systems can be costly, but the payoff is reduced attack surface.
Database privilegesGranting broad rights simplifies deployment.Principle of least privilege limits impact if injection succeeds.

In most modern stacks, the performance cost of safe practices is minimal, while the security benefit is substantial.

Concrete example (MySQL, Node.js)

// Vulnerable code
app.get('/user', (req, res) => {
  const id = req.query.id; // e.g., ?id=5
  const sql = `SELECT * FROM users WHERE id = ${id}`;
  db.query(sql, (err, rows) => {
    if (err) throw err;
    res.json(rows);
  });
});

If an attacker sends ?id=5 OR 1=1, the final query becomes:

SELECT * FROM users WHERE id = 5 OR 1=1

The OR 1=1 clause makes the condition always true, returning all user rows.

Safe version with prepared statements

const sql = 'SELECT * FROM users WHERE id = ?';
db.query(sql, [id], (err, rows) => { … });

The driver treats id as a value, not code, so the injected OR 1=1 is escaped and harmless.

Questions interviewers often ask

  1. “Can you walk me through how the attack works?” – Expect to describe the flow from input to execution, using the example above.
  2. “What are the most common mitigations?” – Mention prepared statements, ORM sanitization, input validation, stored procedures, and least‑privilege DB accounts.
  3. “How would you test for SQL injection in a code review?” – Look for string concatenation, verify that all queries use parameterization, and check that any dynamic SQL is built with safe APIs.
  4. “What would you do if you found a vulnerable endpoint in production?” – Prioritize a quick fix (parameterize the query), add monitoring for anomalous queries, and schedule a deeper refactor.

60‑second spoken answer (ready for the interview)

“SQL injection is when an attacker inserts malicious SQL through user input that the application concatenates directly into a query. The database then executes that injected code, which can expose data or modify the schema. For example, a naive endpoint that builds SELECT * FROM users WHERE id = ${id} will return all rows if someone passes 5 OR 1=1. The standard defense is to use prepared statements or an ORM that automatically sanitizes inputs, combined with least‑privilege database accounts. In a code review I’d flag any string interpolation that reaches the DB and verify that all queries are parameterized.”

How to practice this

  1. Write the vulnerable snippet in a language you know, then refactor it to use prepared statements. Record yourself reciting the 60‑second answer.
  2. Mock an interview with a peer or use Call Assistant to capture your spoken answer and get real‑time feedback on pacing and content.
  3. Create a checklist for code reviews: look for string concatenation, verify parameterization, and note any dynamic SQL that should be wrapped in a safe API.

FAQ

  • What is the difference between SQL injection and NoSQL injection? NoSQL injection exploits similar trust‑boundary flaws but targets query languages used by document stores (e.g., MongoDB). The principle is the same: unsanitized input is interpreted as code.
  • Can prepared statements completely eliminate injection risk? They mitigate the classic injection vector, but developers must still avoid building raw query fragments from user input.
  • Why do some legacy systems still use string concatenation? Historical codebases predate modern ORMs and often lack the resources for a full rewrite, making them vulnerable until a phased migration.
  • Is escaping user input ever sufficient? Escaping can work if done correctly for the specific database dialect, but it’s error‑prone; parameterization is the safer, recommended approach.

Frequently asked questions

What is the difference between SQL injection and NoSQL injection?

NoSQL injection exploits similar trust‑boundary flaws but targets query languages used by document stores (e.g., MongoDB). The principle is the same: unsanitized input is interpreted as code.

Can prepared statements completely eliminate injection risk?

They mitigate the classic injection vector, but developers must still avoid building raw query fragments from user input.

Why do some legacy systems still use string concatenation?

Historical codebases predate modern ORMs and often lack the resources for a full rewrite, making them vulnerable until a phased migration.

Is escaping user input ever sufficient?

Escaping can work if done correctly for the specific database dialect, but it’s error‑prone; parameterization is the safer, recommended approach.

#concept#SQL injection#security#interview#coding