What are the two main SQL injection techniques for data extraction?
WHERE-clause tampering (' OR 1=1--) widens which rows you get back; UNION queries graft on rows from a completely different table.
* The two techniques compared by reach — tampering widens the existing query, UNION grafts on a second one. *
The two differ in how far they reach, and that is the whole point of learning them as a pair: one bends the query you were given, the other bolts a second query onto it.
1. WHERE clause tampering — more rows, same table:
- Modify the WHERE clause by adding
' OR 1=1-- - The condition is now always true, so the filter that was supposed to limit you to your record matches every record instead
- Reach: still only the columns the original query selected — you see all of one table, nothing beyond it
2. UNION query — rows from a different table:
- Append a second SELECT whose results are stacked onto the first result set
- Example: a product search on
NAME LIKE '%…%'becomes
SELECT NAME, DESCRIPTION, PRICE from PRODUCT
where NAME LIKE '%X' UNION ALL SELECT USERNAME, PASSWORD, 0 FROM USER --%'
- Reach: anything the database user can read — here usernames and passwords are returned in the rows below the products
The detail that makes UNION work — and usually fails first: a UNION only compiles if both SELECTs return the same number of columns with compatible types. That is why the injected half ends in a literal 0: the product query selects three columns, so the attacker pads USERNAME, PASSWORD with a third value to line them up. Getting that count right (by trial, or via ORDER BY n) is the practical first step of a UNION attack.
Why the trailing -- in both: it comments out whatever the original query had after the injection point — the closing quote and remaining %' here — so the tampered statement still parses.
Go deeper:
PortSwigger — SQL injection UNION attacks — how to determine the column count and find a text-compatible column.
Wikipedia — SQL injection — the wider family of techniques and notable incidents.