TExcelTAD
Home › SQL › SQL Injection

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:

js
// 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:

sql · try it yourself
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:

sql · try it yourself
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.

js
// JavaScript (sql.js / better-sqlite3 style)
const stmt = db.prepare("SELECT name, city FROM customers WHERE email = ?");
stmt.bind([input]);
python
# Python (sqlite3)
cur.execute("SELECT name, city FROM customers WHERE email = ?", (user_input,))
java
// Java (JDBC)
PreparedStatement ps = conn.prepareStatement(
    "SELECT name, city FROM customers WHERE email = ?");
ps.setString(1, input);
csharp
// 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:

sql · try it yourself
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:

js
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 DROP for 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?

  1. Weak passwords
  2. Building SQL text by concatenating user input
  3. Using SQLite
  4. Missing indexes

What is the recommended defence?

  1. Removing all quotes from input
  2. Parameterized queries / prepared statements
  3. Hiding error messages only
  4. Using stored procedures with string concatenation

Can a table name be passed as a query parameter?

  1. Yes, always
  2. No — use an allow-list for identifiers
  3. Only in PostgreSQL
  4. Only with named parameters