Security Playbook
05 · Web vulnerabilitiesOWASP A05:20258 min read

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.

SQL injection sandbox (fake database)
Query built with
shop.test/login
Try
Query sent to the database
SELECT * FROM users WHERE email = 'ana@mail.test' AND password_ok('wrong-guess')
With parameters the input travels separately from the SQL, so quotes are just characters. The database never runs the attacker's text as code.
A fake login with a fake database. Try the presets in both modes; nothing leaves your browser.

What an attacker can do with it

  • Bypass login: ' OR '1'='1 or admin'-- (comment out the password check).
  • Dump data: UNION SELECT appends 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, DROP if 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}'`); // vulnerable

Then 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