Introduction
In our last lesson, you successfully subverted a web application's login logic to gain unauthorized access. While this is a critical breach, the ultimate goal of an attacker is often data exfiltration. To achieve this, we need to move beyond simply tricking the WHERE clause and start retrieving data from other tables within the database. The primary tool for this is the UNION operator.
This lesson focuses on the first and most crucial step of a UNION-based SQL injection attack. Before you can append data from another table, you must determine the exact number of columns the original, vulnerable query is structured to return. You will learn how to achieve this by injecting ORDER BY clauses and interpreting the application's response to pinpoint the query's structure.
The Foundation of a UNION Attack
The SQL UNION operator allows you to combine the result sets of two or more SELECT statements into a single result set. For an attacker, this means you can attach a query of your own design (e.g., SELECT username, password FROM users) to the application's original query.
However, SQL enforces strict rules for UNION to work:
- Both
SELECTqueries must return the same number of columns. - The data types in each corresponding column must be compatible (e.g., you can't easily combine a text column with a date column).
As a security analyst performing a black-box test, you don't have access to the application's source code, so you don't know the original query. It might be SELECT product_name, price FROM products... (two columns) or SELECT id, name, description, image_path FROM articles... (four columns). Blindly attempting a UNION attack will almost certainly fail because of a column mismatch. Our first task, therefore, is reconnaissance.
To begin, let's get a formal overview of this concept from a definitive source.
SQL injection UNION attacks | Web Security Academy
This article from PortSwigger's Web Security Academy introduces the core principles of UNION-based attacks.
Read the initial section, from the beginning down to the requirements. Pay close attention to the two key requirements for a UNION query to work, as this is the entire premise for today's lesson.
Finding the Column Count with ORDER BY
The ORDER BY clause in SQL is used to sort the results of a query. A useful feature of this clause is that you can specify the column to sort by using its index number rather than its name. For example, ORDER BY 1 sorts by the first column in the SELECT list, ORDER BY 2 sorts by the second, and so on.
This is the feature we will exploit. If we inject an ORDER BY clause and request a column index that exists, the query will execute successfully. However, if we request an index that is out of bounds—for instance, asking to sort by column 5 when the query only returns 4 columns—the database will generate an error. This error, or the lack of one, is the signal we need.
The attack proceeds as follows:
- Append
ORDER BY 1to your injection payload. If the application responds normally, you know there is at least one column. - Increment the number:
ORDER BY 2. If it still works, there are at least two columns. - Continue incrementing the index (
ORDER BY 3,ORDER BY 4, etc.) until the application's response changes. This change could be a visible error message, a generic "Internal Server Error," or simply no results being returned. - The number of columns in the query is the last number that did not produce an error. If
ORDER BY 4causes an error, you have confirmed the query returns three columns.
Let's watch a practical explanation of this technique.
SQL injection Tutorial - Union Based Attack
The video "SQL injection Tutorial - Union Based Attack" clearly explains why finding the number of columns is essential and how the ORDER BY method works.
Watch the segment from on finding column count. The demonstration shows the iterative process of increasing the ORDER BY index until the query breaks, which is exactly the process you will use.
A Practical Walkthrough
Now, let's see this technique applied in a realistic lab scenario. The following video demonstrates how to find the column count on a vulnerable web application, first by explaining the theory and then by executing the attack.
SQL Injection - Lab #3 SQLi UNION attack determining the number of columns returned by the query
In "SQLi UNION attack determining the number of columns", security researcher Rana Khalil walks through this exact process.
First, watch her explanation of the ORDER BY method from the second method. She contrasts it with another technique, but our focus here is on ORDER BY. Next, jump to the hands-on demonstration from the ORDER BY execution. Observe how she injects payloads directly into the browser's URL bar, incrementing the column index from 1 up to 4, and how the application's response changes from sorted results to an error, revealing that the query has three columns.
As you can see from the demonstration, the payload structure is simple. If the injection point is in a WHERE clause like ...WHERE category = 'Gifts', your injected URL parameter would look like this:
...category=Gifts' ORDER BY 1--...category=Gifts' ORDER BY 2--...category=Gifts' ORDER BY 3--...category=Gifts' ORDER BY 4--(This one fails)
Notice the use of the comment -- at the end of the payload. As you learned in the previous lesson, this is crucial for neutralizing the rest of the original query, preventing syntax errors and ensuring your injected clause is the last thing the database processes.
To reinforce your understanding, let's review a written guide that documents this same procedure. Being comfortable with both video and text-based technical documentation is essential for a security analyst.
Exploiting SQL Injection: a Hands-on Example
This article from Acunetix provides another clear, hands-on example of using ORDER BY for column enumeration.
Read the section beginning with the introduction to ORDER BY, and continue through the examples where the author tests ORDER BY 10 (which succeeds) and ORDER BY 11 (which fails), concluding that there are 10 columns.
An Alternative: UNION SELECT NULL
While ORDER BY is a highly reliable technique, it's worth knowing the other common method for enumerating columns: injecting UNION SELECT with NULL values. The logic is similar—you are probing for the correct number of columns—but the approach is different.
You iteratively inject payloads like:
' UNION SELECT NULL--' UNION SELECT NULL,NULL--' UNION SELECT NULL,NULL,NULL--
You continue adding NULLs until the database error disappears, which indicates you have found the correct number of columns. We use NULL because it's a special value that is data-type compatible with almost any column type (text, number, date), satisfying the second rule of UNION.
Rana Khalil's video, which you watched earlier, also contains an excellent demonstration of this method.
SQL Injection - Lab #3 SQLi UNION attack determining the number of columns returned by the query
Let's revisit the video "SQLi UNION attack determining the number of columns" to see the UNION SELECT NULL method in action.
Watch the practical demonstration from the NULL value method. Notice how she uses Burp Suite's Repeater tool to quickly modify and resend the request, adding NULL values until she gets a 200 OK response. This workflow is very common in professional penetration testing.
Conclusion
You have now learned a fundamental reconnaissance technique in SQL injection. By systematically injecting ORDER BY clauses, you can force a database to reveal the number of columns used in a hidden backend query. This is not an attack that yields data on its own, but it is the essential preparatory step that makes sophisticated data exfiltration possible.
Key Takeaways:
- UNION Attack Prerequisite: To use a
UNIONinjection, the number of columns in your injectedSELECTmust match the original query. ORDER BYInjection: You can discover the column count by injectingORDER BY [index]and incrementing the index until the database returns an error.- Interpreting the Signal: The number of columns is the last index that resulted in a successful response before an error occurred.
- Alternative Method: An alternative approach is to inject
' UNION SELECT NULL,NULL,...--payloads, addingNULLvalues until the query succeeds.
In our next lesson, we will put this knowledge to use. Now that you can determine the column count, you will learn how to craft a complete UNION statement to select and retrieve data from tables that were never meant to be seen.