SQLPathLab
Set Operations · Intermediate

UNION

combining result sets and removing duplicates.

Overview

UNION appends the results of several SELECT statements and removes duplicate complete rows. Every branch must return the same number of columns with compatible types in corresponding positions, and final column names normally come from the first SELECT. Deduplication adds work, so prefer UNION ALL when duplicate rows are meaningful or acceptable.

Basic syntax

SELECT name FROM customers UNION SELECT name FROM suppliers;

Examples

UNION example

Combine names from customers and suppliers and observe that a name present in both sources appears once.

Sample table

Table:customers
customers
name
Alice
Bob
Cindy
Table:suppliers
suppliers
name
Alpha
Beta
Alice

Run result

result
name
Alice
Alpha
Beta
Bob
Cindy

Common issues

Can the SELECT branches return different column counts?

No. Corresponding positions need the same number of type-compatible result columns.

Why can UNION be slower?

UNION removes duplicates; when duplicates are acceptable, UNION ALL is usually more direct.

Where should ORDER BY go?

To sort the combined result, place ORDER BY at the end of the complete set query.

Tags

Filtering

Was this explanation clear?