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
customers| name |
|---|
| Alice |
| Bob |
| Cindy |
suppliers| name |
|---|
| Alpha |
| Beta |
| Alice |
Run result
| name |
|---|
| Alice |
| Alpha |
| Beta |
| Bob |
| Cindy |
Common issues
No. Corresponding positions need the same number of type-compatible result columns.
UNION removes duplicates; when duplicates are acceptable, UNION ALL is usually more direct.
To sort the combined result, place ORDER BY at the end of the complete set query.
Tags
Was this explanation clear?
Thanks. This feedback will inform the next content review.