Course contentsShow
← Computer Science
Lesson 2477 of 2,87255. Web SecurityFree lesson

Union-Based SQL Injection

Using UNION SELECT statements to extract data from other database tables through vulnerable queries.

Union-Based SQL Injection

You'll learn how attackers use the SQL UNION operator to combine malicious queries with legitimate ones, extracting sensitive data from other database tables.

What Is Union-Based SQL Injection?

Union-based SQL injection exploits the SQL UNION operator, which combines results from multiple SELECT statements. When an application doesn't properly validate input, attackers can inject a UNION SELECT statement that appends data from other tables to the original query's results—effectively stealing information that was never meant to be displayed.

How It Works

Imagine a vulnerable search feature:

SELECT product_name, price FROM products WHERE category = 'user_input'

An attacker provides input like:

' UNION SELECT username, password FROM users--

The resulting query becomes:

SELECT product_name, price FROM products WHERE category = '' UNION SELECT username, password FROM users--'

The database now returns both product data and usernames/passwords together. The comment (--) ignores everything after, avoiding syntax errors.

Key Requirements

For UNION-based injection to work:

  1. Column count must match: Both SELECT statements need the same number of columns
  2. Data types must be compatible: Corresponding columns should have similar types

Attackers often probe with:

' UNION SELECT NULL, NULL-- (testing 2 columns)
' UNION SELECT NULL, NULL, NULL-- (testing 3 columns)

Once they find the right count, they replace NULL values with actual table/column names to extract data.

Real-World Impact

This technique can expose entire databases—customer records, credentials, financial data—through a single vulnerable input field. Unlike error-based injection, it works even when error messages are hidden.

Key Takeaway: Union-based SQL injection leverages the UNION operator to merge malicious queries with legitimate ones, extracting unauthorized data by matching column counts and data types—making parameterized queries essential for defense.