Lesson 8 of 15 · 19 min · Beginner

SQL injection

How SQL injection works, finding it with errors and behaviour, union, boolean and time-based techniques, second-order and NoSQL injection, using sqlmap responsibly and the parameterised-query fix.

In this lesson you will

  • Explain how user input becomes part of a SQL query
  • Detect SQL injection through errors, behaviour changes and timing
  • Prove impact with union, boolean and time-based techniques in a lab
  • Recommend parameterised queries and explain why filtering fails

SQL injection (SQLi) is over 25 years old and still appears in real applications every year. It happens when user input is pasted into a database query instead of being passed separately as data.

How it happens

The developer writes:

text
query = "SELECT * FROM products
         WHERE category = '" + input + "'"

Normal input Gifts gives:

sql
SELECT * FROM products WHERE category = 'Gifts'

Input Gifts' OR '1'='1 gives:

sql
SELECT * FROM products WHERE category = 'Gifts' OR '1'='1'

The quote closed the string and the rest became SQL code. Every row is returned.

text
 input ──► string concatenation ──► SQL
          (data becomes code ✗)

 input ──► parameter (?) ──────────► SQL
          (data stays data ✓)

Step 1: find candidate inputs

Anything that might reach a database: search boxes, IDs, filters, sort orders, login fields, cookies, headers, JSON fields.

Step 2: probe

Send these one at a time in Repeater and watch the response:

Probe What you're looking for
' SQL error or 500
'' Error disappears again
' AND '1'='1 Same as normal
' AND '1'='2 Different (fewer results)
1 AND 1=1 / 1 AND 1=2 Same for numeric inputs
ORDER BY column (id vs 9) Error on invalid column number

True vs false behaving differently is the strongest signal. Errors are a bonus, not a requirement.

Step 3: identify the type

text
          SQL injection
   ┌──────────┼───────────┐
 In-band    Blind       Out-of-band
 │          │           (DNS / HTTP
 ├ error    ├ boolean    callbacks)
 └ union    └ time

Union-based (in-band)

When results appear on the page, UNION appends rows from another query.

  1. Find the number of columns: ' ORDER BY 1--, ' ORDER BY 2--, ... until it errors.
  2. Find which columns display text: ' UNION SELECT NULL,'a',NULL--.
  3. Read harmless proof data, such as the database version:
sql
' UNION SELECT NULL, @@version, NULL--

Version syntax differs: @@version (MySQL, SQL Server), version() (PostgreSQL), sqlite_version() (SQLite).

Boolean-based blind

No results or errors shown, but the page changes between true and false. You can ask yes/no questions:

sql
' AND SUBSTRING(@@version,1,1)='8'--

Page normal → yes. Page different → no.

Time-based blind

Nothing visible changes at all, so make the database wait:

sql
' AND SLEEP(5)--            -- MySQL
'; SELECT pg_sleep(5)--     -- PostgreSQL
'; WAITFOR DELAY '0:0:5'--  -- SQL Server

A 5-second delay that appears only with your payload confirms injection. Repeat it a few times to rule out network lag.

Second-order SQL injection

Input is stored safely, then used unsafely later. Register the username alice'--, and a later password-change feature might build a query with it. Test stored values in every feature that reuses them.

NoSQL injection

Document databases such as MongoDB are injectable too, with operators instead of quotes:

json
{"username": "admin", "password": {"$ne": null}}

"Password not equal to null" is true for every account. Test JSON inputs with operators like $ne, $gt and $regex.

Using sqlmap responsibly

sqlmap automates detection and exploitation. Use it to confirm what you found by hand, not to spray a target.

bash
sqlmap -r request.txt -p id --batch --level 2 --risk 1
  • -r reads a request saved from Burp; -p targets one parameter.
  • Keep --risk 1 on real engagements: higher levels can modify data.
  • Never dump real tables. Prove the bug with the version or current user, and stop.

Proving impact in a report

Good proof is minimal: the database version, the current database user, or the number of rows in a table. That proves an attacker could read everything without you reading everything.

Severity is usually critical when unauthenticated, because SQLi often exposes the entire database, and sometimes allows file access or command execution.

The fix

Defence Verdict
Parameterised queries / prepared statements ✅ The fix
ORM used correctly ✅ Good (watch raw-query helpers)
Allow-lists for sort columns and table names ✅ Needed where parameters can't be used
Least-privilege database account ✅ Limits damage
Escaping or blocking quotes ⚠️ Fragile, often bypassed
WAF only ⚠️ A speed bump, not a fix

Example of the fix (any language has an equivalent):

text
db.query("SELECT * FROM products
          WHERE category = ?", [input])

Lab

  1. DVWA (SQL Injection, low): find the number of columns, then display the database version with a UNION query.
  2. DVWA (SQL Injection (Blind), low): confirm injection with a time delay.
  3. Juice Shop: log in as the admin without knowing the password using the login form.
  4. PortSwigger Academy: complete SQL injection vulnerability in WHERE clause allowing retrieval of hidden data and SQL injection UNION attack, determining the number of columns.
  5. Save one request from Burp and confirm the DVWA finding with sqlmap -r, then write the finding with the fix.

Checkpoint

  1. Why does a single quote break a vulnerable query?
  2. What's the strongest signal of SQL injection when there are no errors?
  3. When would you use a time-based technique?
  4. What is second-order SQL injection?
  5. Why is escaping quotes not a reliable fix?