SQL UNION Operator

The SQL UNION Operator

The UNION operator is used to combine the result-set of two or more SELECT statements.


UNION Syntax

SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;

By default, the UNION operator selects only distinct (unique) values. If you want to allow duplicate values, use UNION ALL.


Demo Database

Customers Table:

CustomerID CustomerName Country
1 Alfreds Futterkiste Germany
2 Ana Trujillo Emparedados Mexico

Suppliers Table:

SupplierID SupplierName Country
1 Exotic Liquids UK
2 New Orleans Cajun Delights USA
3 Grandma Kelly's Homestead USA

UNION Example

The following SQL statement returns the cities (only distinct values) from both the "Customers" and the "Suppliers" table.

UNION Example

SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;

UNION with WHERE

The following SQL statement returns the German cities (only distinct values) from both the "Customers" and the "Suppliers" table.

UNION with WHERE Example

SELECT City, Country FROM Customers
WHERE Country = 'Germany'
UNION
SELECT City, Country FROM Suppliers
WHERE Country = 'Germany'
ORDER BY City;