SQL Injection
SQL injection is a security flaw that happens when an application builds SQL text by pasting user input into it. A malicious user can then type input that changes the meaning of the query — reading other people's data, bypassing a login or deleting tables. It has been one of the most common web vulnerabilities for decades, and it is completely preventable.
How it happens
Imagine a shop page that looks up a customer by e-mail. The (bad) server code glues the input into the query:
// DON'T DO THIS
const sql = "SELECT name, city FROM customers WHERE email = '" + input + "'";
db.exec(sql);With a normal input such as ava.nguyen@example.com, the query is fine:
SELECT name, city FROM customers WHERE email = 'ava.nguyen@example.com';name | city
------------+-------
Corner Cafe | Berlin
(1 row)
Now an attacker types x' OR '1'='1 into the box. After concatenation, the database receives:
SELECT name, city FROM customers WHERE email = 'x' OR '1'='1'
ORDER BY name LIMIT 5;name | city
--------------+-------
Amara Costa | Lagos
Arjun Sharma | Oslo
Bright Bytes | Paris
Code & Coffee | Tokyo
Corner Cafe | Berlin
(5 rows)
The quote in the input closed the string early, and the rest became SQL. '1'='1' is always true, so every customer is returned. (We added ORDER BY … LIMIT 5 only to keep the output short.)
Comments make it worse: input like ' OR 1=1 -- turns the remainder of the original query into a comment, removing any extra conditions such as AND password = ….
The fix: parameterized queries
Never put user input into SQL text. Use placeholders and pass the values separately. The database then treats the value strictly as data — a quote inside it is just a character, never the end of a string.
// JavaScript (sql.js / better-sqlite3 style)
const stmt = db.prepare("SELECT name, city FROM customers WHERE email = ?");
stmt.bind([input]);# Python (sqlite3)
cur.execute("SELECT name, city FROM customers WHERE email = ?", (user_input,))// Java (JDBC)
PreparedStatement ps = conn.prepareStatement(
"SELECT name, city FROM customers WHERE email = ?");
ps.setString(1, input);// C# (ADO.NET)
var cmd = new SqlCommand("SELECT name, city FROM customers WHERE email = @email", conn);
cmd.Parameters.AddWithValue("@email", input);With a parameter, the malicious input is simply compared as text. It is equivalent to this query, where the whole input is one string value:
SELECT name, city FROM customers WHERE email = 'x'' OR ''1''=''1';name | city
-----+-----
(0 rows)
No customer has that strange e-mail, so nothing is returned — the attack is harmless.
Placeholder styles
| Driver / language | Placeholder |
|---|---|
| SQLite, JDBC, ODBC | ? |
| SQLite (named) | :email, @email, $email |
| PostgreSQL (libpq, node-postgres) | $1, $2 |
| Python psycopg / MySQL connectors | %s (still a parameter, not string formatting!) |
| .NET | @name |
What parameters cannot do
Placeholders stand for values only. Table names, column names and keywords like ASC/DESC cannot be parameters. If users can choose a sort column, compare their choice against a fixed allow-list in your code:
const allowed = { name: "name", price: "price" };
const column = allowed[userChoice] ?? "name"; // never the raw input
const sql = `SELECT name, price FROM products ORDER BY ${column}`;Defence in depth
- Parameterize every query — also in internal tools and admin pages.
- Use an ORM or query builder that parameterizes for you (and avoid its "raw SQL" escape hatches with user input).
- Give the application's database user only the permissions it needs (no
DROPfor a read-only report). - Validate input (type, length, format) — as an extra layer, not a replacement.
- Don't show raw database error messages to users; they help attackers.
Note: "Escaping" quotes by hand (
replace("'", "''")) is fragile and easy to get wrong across character sets and dialects. Parameters are the real solution.
Test yourself
What is the root cause of SQL injection?
- Weak passwords
- Building SQL text by concatenating user input
- Using SQLite
- Missing indexes
What is the recommended defence?
- Removing all quotes from input
- Parameterized queries / prepared statements
- Hiding error messages only
- Using stored procedures with string concatenation
Can a table name be passed as a query parameter?
- Yes, always
- No — use an allow-list for identifiers
- Only in PostgreSQL
- Only with named parameters