Set Operations
Lesson 13 of 20UNION stacks, INTERSECT overlaps, EXCEPT subtracts — combine whole result grids like building blocks.
Combining whole results
WHERE filters rows inside one query. Set operators do something bigger: they take two entire query results and stack, overlap or subtract them.
UNION
Glues two result grids on top of each other and removes duplicate rows.
UNION ALL
Same stacking, but duplicates stay. It is faster because nothing is checked.
INTERSECT and EXCEPT
INTERSECT keeps rows present in both results; EXCEPT keeps rows from the first that miss the second.
The one rule
Both queries must return the same number of columns, with compatible types.
Four operators, one script
Press play: two small lists are built first, then combined with UNION ALL, UNION, INTERSECT and EXCEPT.
1-- List 1: everyone in Sales2SELECT name FROM employees3WHERE dept = 'Sales';4-- List 2: everyone earning over 600005SELECT name FROM employees6WHERE salary > 60000;78-- UNION ALL: stack both lists, duplicates stay9SELECT name FROM employees WHERE dept = 'Sales'10UNION ALL11SELECT name FROM employees WHERE salary > 60000;1213-- UNION: stack both lists, duplicates removed14SELECT name FROM employees WHERE dept = 'Sales'15UNION16SELECT name FROM employees WHERE salary > 60000;1718-- INTERSECT: names found in BOTH lists19SELECT name FROM employees WHERE dept = 'Sales'20INTERSECT21SELECT name FROM employees WHERE salary > 60000;2223-- EXCEPT: names in list 1 but NOT in list 224SELECT name FROM employees WHERE dept = 'Sales'25EXCEPT26SELECT name FROM employees WHERE salary > 60000;
The first query lists the Sales employees and returns two names.
Which set operator do you need?
Follow the questions: duplicates, overlap, or differences — one keyword matches each need.
Match the set operators
Click an operator, then click its job to lock the pair.
Predict the intersection
Two filters, one INTERSECT between them. Which names survive?
1SELECT name FROM employees2WHERE dept = 'Marketing'3INTERSECT4SELECT name FROM employees5WHERE salary > 60000;
Hint: Marketing holds only Finn — and 62000 is over 60000, so he appears in both lists and survives INTERSECT.
Key takeaways
UNION stacks results; UNION ALL is faster because it skips duplicate removal.
INTERSECT is the overlap; EXCEPT is the difference (first set minus second).
Both queries must return the same number of compatible columns.
Want every row, duplicates included? Say UNION ALL out loud.
Set operators combine whole results — WHERE only filters inside one result.