Set Operations
UNION, UNION ALL, INTERSECT and EXCEPT stack or compare the rows of two queries. Know how each treats duplicates and NULLs, and how they bind when mixed.
Overview
A set operation takes the rows of two SELECT queries and combines them into one result. The two queries must be union compatible: the same number of columns, with compatible types in each position. The result's column names come from the first query.
There are four of them. Three remove duplicate rows by default, and one keeps them.
- UNION returns the rows in either query, with duplicates removed.
- UNION ALL returns every row of both queries, stacked, with duplicates kept.
- INTERSECT returns the rows in both queries, with duplicates removed. INTERSECT ALL keeps some of them.
- EXCEPT returns the rows in the first query and not in the second, with duplicates removed. EXCEPT ALL keeps some of them.
Oracle spells EXCEPT as MINUS; its 21c manual also accepts EXCEPT as a synonym. MySQL added INTERSECT and EXCEPT only in 8.0.31.
Whichever operator you use, the work happens in the same order.
- The first query runs on its own, for example SELECT email ... from web_signups.
- The second query runs on its own, for example SELECT email ... from store_signups.
- The operator, UNION, INTERSECT or EXCEPT, compares whole rows, column by column.
- One result comes out, with its columns named by the first query.
The four operations on one example
Two small tables of sign-up emails. Ben signed up twice on the web and once in a store.
Run the same pair of queries with each operator and you get these rows.
- UNION: ana, ben, cy, dee. Ben's three sign-ups collapse into one row.
- UNION ALL: ana, ben, ben, ben, cy, dee, which is 6 rows, all four web rows plus both store rows.
- INTERSECT: ben, the only email in both tables.
- EXCEPT: ana, cy. Ben is removed because he is also in the store table.
- EXCEPT ALL: ana, ben, cy. One of Ben's two web rows is canceled out by his one store row, and the other survives.
UNION ALL is the cheapest: the database only appends rows. The other three must find duplicates, which means a sort or a hash over the combined rows. So use UNION ALL whenever duplicates are impossible or harmless, and UNION only when you want them removed.
Sign up free to read the full topic
More Databases & SQL topics
Start free on Cariara · Coding problems · System design studio