SQL injection: when user input becomes code
Building SQL by gluing strings together lets an attacker close your quote and write their own query. How it works, what it can do, and the one fix that actually solves it: parameters.
In one sentence
If user input is concatenated into a query, a single quote turns data into SQL. Parameterized queries keep data and code apart, so the attacker's text is only ever text.
The idea
The database receives one string and has no way to know which parts you wrote and which parts came from the user. If the email field contains ' OR '1'='1, the query's meaning changes: the condition becomes always true.
SELECT * FROM users WHERE email = 'ana@mail.test' AND password_ok('wrong-guess')What an attacker can do with it
- Bypass login:
' OR '1'='1oradmin'--(comment out the password check). - Dump data:
UNION SELECTappends rows from any table the DB user can read. - Blind extraction: when nothing is shown, ask yes/no questions and measure the response or its timing.
- Change or delete data: stacked queries,
UPDATE,DROPif the driver and permissions allow it.
The fix: parameters, not escaping
Vulnerable
- db.query("SELECT * FROM users WHERE email = '" + email + "'")
- Template strings are the same problem:
WHERE email = '${email}'
Safe
- db.query("SELECT * FROM users WHERE email = $1", [email])
- ORMs and query builders parameterize for you (until you use their raw() escape hatch)
// Prisma / Drizzle / Knex parameterize normal queries
await db.user.findFirst({ where: { email } });
// Raw SQL: use the tagged template, never string concatenation
await prisma.$queryRaw`SELECT * FROM users WHERE email = ${email}`; // safe
await prisma.$queryRawUnsafe(`SELECT * FROM users WHERE email = '${email}'`); // vulnerableThen add layers: a DB user that can't read tables it doesn't need, generic error messages (SQL errors in the response help attackers), and alerts on unusual query volume.
Key takeaways
- 01Injection happens when input is concatenated into a query or command.
- 02Parameterized queries are the fix; escaping by hand is not.
- 03Identifiers like column names need an allowlist.
- 04The same idea applies to shell commands, LDAP, NoSQL and LLM prompts.
Check your understanding
1 of 3
When does SQL injection happen?
Related concepts
Defense in depth
Every control has holes. Line up several independent ones and the holes rarely align: the Swiss cheese model.
6 min read →Least privilege
Assume something will get hacked. Least privilege makes sure that when it does, the attacker gets the keys to one room, not the whole building.
6 min read →XSS
XSS is injection into HTML instead of SQL. Escape output by default, never inject raw HTML, and add a Content Security Policy as the safety net.
8 min read →