Course contentsShow
← Security
Lesson 566 of 3,05213. Web Security - Injection AttacksFree lesson

Union-Based SQL Injection Technique

Using UNION SELECT to combine malicious queries and extract data from other tables.

Union-Based SQL Injection Technique

What you'll learn: How attackers use SQL's UNION operator to combine legitimate queries with malicious ones, extracting sensitive data from unintended database tables.

How UNION Works (Legitimately)

In SQL, the UNION operator merges results from two separate SELECT statements into one result set. Think of it like stacking two identical spreadsheets on top of each other — both must have the same number of columns and compatible data types.

SELECT name, email FROM users
UNION
SELECT product, description FROM inventory

The Attack Technique

Attackers exploit vulnerable input fields by injecting a UNION SELECT statement that extracts data from tables the application never intended to query.

Example vulnerable query:

SELECT title, description FROM articles WHERE id = [USER_INPUT]

Attacker's injection:

1 UNION SELECT username, password FROM admin_users--

Resulting query executed:

SELECT title, description FROM articles WHERE id = 1 
UNION 
SELECT username, password FROM admin_users--

The application displays article data AND admin credentials together as if they're all legitimate articles!

Why This Works

The application blindly trusts user input and concatenates it directly into the SQL query. The attacker's UNION SELECT appends their malicious query, while the -- comment symbol ignores everything after it, preventing syntax errors.

Key Requirements

For UNION-based injection to succeed:

  • The injected query must have the same number of columns as the original
  • Column data types must be compatible
  • The application must display or return query results

Key Takeaway: Union-based SQL injection leverages the UNION operator to append malicious SELECT statements, allowing attackers to extract data from any database table by combining it with legitimate query results — making stolen data appear as normal application output.