SQL UNION, INTERSECT and EXCEPT
What you will learn
- How
UNIONandUNION ALLstack two results - How
INTERSECTkeeps the rows found in both - How
EXCEPTkeeps the rows found in the first only - The rules for the two queries, and how to sort the result
This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). Edit any query and press Run. Reset data puts the original rows back.
1. Stacking results
A join puts tables side by side. A set operator stacks the result of one query under the result of another. The two queries must return the same number of columns, with compatible types, and the column names of the result come from the first query.
Two lists of countries: where customers live and where suppliers are based.
SELECT country FROM customers
UNION
SELECT country FROM suppliers
ORDER BY country LIMIT 8;
country
----------
Bangladesh
Brazil
Canada
Egypt
Ghana
India
Japan
Kenya
(8 rows)
Two lists of cities: where customers live and where the bank has branches.
SELECT city FROM customers
UNION
SELECT city FROM branches
ORDER BY city LIMIT 8;
city
--------
Accra
Austin
Cairo
Dhaka
Hanoi
Istanbul
Lagos
Leeds
(8 rows)
Two lists of last names: students enrolled in 2023 and students enrolled in 2026.
SELECT last_name FROM students WHERE enrolled_year = 2023
UNION
SELECT last_name FROM students WHERE enrolled_year = 2026
ORDER BY last_name LIMIT 8;
last_name
---------
Abdi
Ahmed
Alvarez
Banerjee
Bianchi
Chowdhury
Cohen
Costa
(8 rows)
UNION removes duplicate rows from the combined result, like DISTINCT. A value found in both lists appears once.
2. UNION ALL keeps everything
UNION ALL stacks the results without removing duplicates. It is faster and keeps the true row count, so use it when the two queries cannot overlap or when the duplicates matter:
SELECT (SELECT COUNT(*) FROM (SELECT country FROM customers UNION SELECT country FROM suppliers)) AS union_rows,
(SELECT COUNT(*) FROM (SELECT country FROM customers UNION ALL SELECT country FROM suppliers)) AS union_all_rows,
(SELECT COUNT(*) FROM customers) + (SELECT COUNT(*) FROM suppliers) AS customers_plus_suppliers;
union_rows union_all_rows customers_plus_suppliers
---------- -------------- ------------------------
16 430 430
(1 row)
SELECT (SELECT COUNT(*) FROM (SELECT city FROM customers UNION SELECT city FROM branches)) AS union_rows,
(SELECT COUNT(*) FROM (SELECT city FROM customers UNION ALL SELECT city FROM branches)) AS union_all_rows,
(SELECT COUNT(*) FROM customers) + (SELECT COUNT(*) FROM branches) AS customers_plus_branches;
union_rows union_all_rows customers_plus_branches
---------- -------------- -----------------------
16 306 306
(1 row)
SELECT (SELECT COUNT(*) FROM (SELECT last_name FROM students WHERE enrolled_year = 2023 UNION SELECT last_name FROM students WHERE enrolled_year = 2026)) AS union_rows,
(SELECT COUNT(*) FROM (SELECT last_name FROM students WHERE enrolled_year = 2023 UNION ALL SELECT last_name FROM students WHERE enrolled_year = 2026)) AS union_all_rows,
(SELECT COUNT(*) FROM students WHERE enrolled_year IN (2023, 2026)) AS students_from_both_years;
union_rows union_all_rows students_from_both_years
---------- -------------- ------------------------
45 172 172
(1 row)
UNION ALL gives the sum of the two row counts. UNION gives fewer, because duplicates were removed.
3. INTERSECT: found in both
INTERSECT keeps only the rows that appear in both results (each once):
Countries where there are both customers and suppliers:
SELECT country FROM customers
INTERSECT
SELECT country FROM suppliers
ORDER BY country;
country
--------------
Canada
Egypt
Ghana
India
Japan
Kenya
Peru
Portugal
United Kingdom
Vietnam
(10 rows)
Cities where there are both customers and a branch:
SELECT city FROM customers
INTERSECT
SELECT city FROM branches
ORDER BY city;
city
-------
Cairo
Lagos
Lisbon
Osaka
Pune
Toronto
(6 rows)
Last names found among students of 2023 and of 2026:
SELECT last_name FROM students WHERE enrolled_year = 2023
INTERSECT
SELECT last_name FROM students WHERE enrolled_year = 2026
ORDER BY last_name LIMIT 8;
last_name
---------
Abdi
Alvarez
Chowdhury
Cohen
Costa
Das
Diaz
Eze
(8 rows)
4. EXCEPT: in the first only
EXCEPT keeps the rows of the first query that do not appear in the second. The order of the queries matters:
Countries with customers but no supplier:
SELECT country FROM customers
EXCEPT
SELECT country FROM suppliers
ORDER BY country;
country
-------------
Bangladesh
Brazil
Nigeria
Philippines
Turkey
United States
(6 rows)
Cities with customers but no branch:
SELECT city FROM customers
EXCEPT
SELECT city FROM branches
ORDER BY city;
city
------------
Accra
Austin
Dhaka
Hanoi
Istanbul
Leeds
Lima
Manila
Nairobi
Porto Alegre
(10 rows)
Last names of 2023 students that are not found among the 2026 students:
SELECT last_name FROM students WHERE enrolled_year = 2023
EXCEPT
SELECT last_name FROM students WHERE enrolled_year = 2026
ORDER BY last_name;
last_name
---------
Ahmed
Ito
Rahman
Reyes
Zhang
(5 rows)
Swap the two queries and you get a different answer (the other side's rows). EXCEPT is another way to find missing rows (lesson 4.4).
5. The rules
- Both queries return the same number of columns, in a compatible order.
- The result takes its column names from the first query.
ORDER BY(andLIMIT) apply to the whole result and go once, at the end.- Set operators treat
NULLs as equal to each other (unlike=): twoNULLs are one duplicate. - You can chain several operators; use brackets (or subqueries) when you mix different ones, because the order of evaluation can surprise you.
Two NULLs count as the same value for a set operator:
SELECT NULL AS value UNION SELECT NULL;
value
-----
NULL
(1 row)
SELECT NULL AS value UNION SELECT NULL;
value
-----
NULL
(1 row)
SELECT NULL AS value UNION SELECT NULL;
value
-----
NULL
(1 row)
One row: the two NULLs were treated as one duplicate.
A common use of UNION ALL is to put labels on rows of different tables so that they can share one list:
SELECT 'customer' AS source, country AS place FROM customers WHERE customer_id <= 2
UNION ALL
SELECT 'supplier', country FROM suppliers WHERE supplier_id <= 2
ORDER BY source, place;
source place
-------- --------------
customer United Kingdom
customer United Kingdom
supplier Portugal
supplier Vietnam
(4 rows)
SELECT 'customer' AS source, city AS place FROM customers WHERE customer_id <= 2
UNION ALL
SELECT 'branch', city FROM branches WHERE branch_id <= 2
ORDER BY source, place;
source place
-------- -------
branch Lisbon
branch Toronto
customer Lima
customer Manila
(4 rows)
SELECT 'student' AS source, last_name AS name FROM students WHERE student_id <= 2
UNION ALL
SELECT 'teacher', name FROM teachers WHERE teacher_id <= 2
ORDER BY source, name;
source name
------- ------------
student Haque
student Khan
teacher Noah Fischer
teacher Omar Mahmud
(4 rows)
Worked example: choose the operator
| Question | Operator |
|---|---|
| "one list of all cities, each once" | UNION |
| "every row of both tables, keep duplicates" | UNION ALL |
| "cities that appear in both tables" | INTERSECT |
| "cities in the first table but not in the second" | EXCEPT |
The tables are made up.
Common mistakes
- A different number of columns in the two queries.
- Using
UNIONwhenUNION ALLis meant, which silently removes rows (and is slower). - An
ORDER BYinside the first query only, instead of once at the end. - Swapping the two queries of
EXCEPT. - Forgetting the column names come from the first query.
Key takeaways
UNIONstacks and removes duplicates;UNION ALLstacks and keeps them.INTERSECTkeeps rows found in both;EXCEPTkeeps rows found in the first only.- Both queries need the same number of compatible columns;
ORDER BYgoes once at the end. - Joins combine side by side; set operators combine one under the other.
Practice
1. What is the difference between UNION and UNION ALL?
Show answer
UNION removes duplicate rows; UNION ALL keeps them all.
2. Which operator returns the rows found in both queries?
Show answer
INTERSECT.
3. What does A EXCEPT B return?
Show answer
The rows of A that are not in B.
4. Where does ORDER BY go in a UNION?
Show answer
Once, at the very end; it sorts the whole combined result.
5. Can you UNION a query with two columns and a query with three?
Show answer
No. Both must return the same number of columns.
6. Which operator is a way to find missing rows?
Show answer
EXCEPT: the keys in the first table that are not in the second.