July 25, 2026
SQL Injection UNION Attack: Determining the Number of Columns Returned by the Query
Platform: PortSwigger Web Security Academy Category: SQL Injection Difficulty: Practitioner
By Betty Guta
1 min read
Introduction
As I continued learning SQL injection through PortSwigger Web Security Academy, I came across this lab on UNION attacks. Before extracting any useful information with a UNION-based SQL injection, it's important to know how many columns the original SQL query returns.
Lab Objective
The goal of this lab is to determine the number of columns returned by the application's SQL query using a UNION SELECT statement. Once the correct number of columns is identified, it's possible to move on to more advanced UNION attacks that retrieve data from the database.
My Approach
I started by interacting with the application's category filter since it accepted user input. Instead of guessing the number of columns, I tested different UNION SELECT statements using NULL values as placeholders.
I began with one NULL, then gradually increased the number until the application stopped returning an error and loaded the page normally.
For example: ' UNION SELECT NULL — , If that failed i tried -> ' UNION SELECT NULL,NULL — , and continued increasing the number of NULL values until i found the correct column count.
Using NULL is a common technique because it works with most SQL data types, making it safe placeholder during testing.
What I Learned
one of the biggest lessons from this lab is that a UNION SELECT statement must match the original query's structure. If the number of columns doesn't match, the database rejects the query.
This explains why attackers first determine the number of columns before attempting to retrieve data such as usernames, passwords, or other sensitive information.
How Developers Can Prevent This
The best way to prevent SQL injection is to avoid inserting user input directly into SQL queries.
Developers should:
- Use parametrized queries.
- Validate and sanitize user input.
- Avoid displaying detailed database error messages.
Skills Practiced
- SQL Injection
- UNION-based SQL Injection
- Web Application Testing
- Database Enumeration
Conclusion
This lab helped me better understand the logic behind UNION-based SQL injection rather than simply memorizing payloads.