Home / SQL / Reference / Subqueries, CTEs and sets

SQL UNION and UNION ALL

Stack the results of two queries.

Syntax

SELECT …
UNION [ALL]
SELECT …

Both queries need the same number of columns. UNION removes duplicates; UNION ALL keeps them (and is faster).

Example

Query (on the shop database used in the SQL course)

SELECT city AS place FROM customers WHERE city IS NOT NULL
UNION
SELECT country FROM customers
ORDER BY place;

Result

place
Auckland
Australia
Brisbane
Kathmandu
London
Melbourne
Nepal
New Zealand
Sydney
United Kingdom

10 rows

Related

Learn it step by step in the free lesson Subqueries & Set Operations, with exercises that check your queries.