Set operations
Joins combine tables sideways — more columns. Set operations combine them downwards — more rows. They are the smaller half of the toolkit and they come up in interviews mainly through one performance question and one correctness question, both below.
The rules they all share
Every set operation requires the two queries to agree on:
- the same number of columns
- compatible types, column by column, by position
Names are not checked. The output takes its column names from the first query, so the second query’s aliases are decoration.
SELECT name FROM employee
UNION
SELECT id, name FROM department;
ERROR: each UNION query must have the same number of columns
Position, not name, is what matches — the same rule the result comparator in this track’s problems uses, and for the same reason: names are a human convenience and positions are the contract.
UNION ALL versus UNION
SELECT building FROM department
UNION ALL
SELECT building FROM department;
Eight rows, duplicates and nulls included — it concatenates.
SELECT building FROM department
UNION
SELECT building FROM department;
Three rows. UNION deduplicates, and that is not free: the engine has to
sort or hash every row to find duplicates. On a large result that is the
dominant cost of the query.
UNION ALL is the right default. Reach for plain UNION only when you
actually need duplicates removed, and when you do, know that you are paying for
a sort. The common mistake is the reverse — writing UNION by habit over two
queries that cannot overlap by construction, and paying for a deduplication
that removes nothing.
Note the nulls deduplicated too: UNION treats two nulls as the same row, the
“not distinct” semantics from the NULL lesson
rather than =.
EXCEPT — rows in the first query and not the second
SELECT id FROM department
EXCEPT
SELECT department_id FROM employee;
Research’s id, 4. Compare that with the NOT IN version from the previous
lesson, which returned nothing because of a null: EXCEPT is null-safe,
because it compares rows rather than evaluating a predicate per value.
So there are now four ways to write an anti-join, and it is worth knowing why you would pick each:
| Form | Null-safe | Notes |
|---|---|---|
NOT EXISTS |
yes | the default; plans well, reads clearly |
LEFT JOIN ... IS NULL |
yes | when you also want columns from the left |
EXCEPT |
yes | cleanest when you want only the key, deduplicated |
NOT IN |
no | avoid with nullable columns |
EXCEPT also deduplicates, so EXCEPT ALL exists for when you want multiset
difference and the counts matter.
INTERSECT — rows in both
SELECT building FROM department
INTERSECT
SELECT 'Riverside';
One row. Useful for “present in both sources” checks; much rarer than the other two in application code, because a join usually answers the same question while keeping the columns you need.
Ordering and the one syntax gotcha
ORDER BY applies to the whole result, not to one branch, and it goes at
the end:
SELECT name, salary FROM employee WHERE department_id = 1
UNION ALL
SELECT name, salary FROM employee WHERE department_id = 2
ORDER BY salary DESC;
To order or limit a single branch you have to parenthesise it, because otherwise the clause binds to the combined result:
(SELECT name, salary FROM employee ORDER BY salary DESC LIMIT 2)
UNION ALL
(SELECT name, salary FROM employee ORDER BY salary ASC LIMIT 2)
ORDER BY salary DESC;
Top two and bottom two, then sorted together. Without the parentheses this is
either a syntax error or — worse, in some engines — a query that silently
applies the LIMIT to everything.
When this comes up in real systems
Set operations are how you stitch together partitioned or archived data: a
hot table and a cold table with the same shape, combined with UNION ALL behind
a view. That is also the one case where the ALL matters most, because the two
sides cannot overlap by construction and a deduplicating UNION would sort the
entire history for nothing.
It is also the standard reconciliation tool — EXCEPT in both directions
answers “what does each side have that the other does not”, which is the
FULL OUTER JOIN question from the joins lesson
asked a different way.
Try it
The UNION versus UNION ALL pair is the one to run in the
SQL playground — eight rows against three on four rows
of input makes the deduplication visible.
Drill the anti-join forms with
Find orphaned rows, which
stacks two anti-joins with UNION ALL.
Partitioning a hot table from a cold one is a storage-design decision before it is a SQL one; SQL vs NoSQL and the HLD fundamentals cover that side.
Interview questions
1. What is the difference between UNION and UNION ALL, and which should be
the default?
UNION removes duplicate rows, UNION ALL does not. UNION ALL should be the
default because deduplication requires a sort or hash over the whole result, and
most unions combine sets that cannot overlap anyway.
2. What must two queries agree on for a set operation to be legal? The same number of columns and compatible types position by position. Column names are not checked; the result takes the first query’s names.
3. Give three ways to find rows in A with no match in B, and say which is
unsafe.
NOT EXISTS, LEFT JOIN ... WHERE B.key IS NULL, and EXCEPT. NOT IN is
unsafe against a nullable column, where it returns no rows at all.
4. Does UNION treat two NULLs as duplicates?
Yes. Set operations and GROUP BY use “not distinct” semantics, under which two
nulls match, unlike = in a WHERE clause.
5. How do you take the top two rows of one query and the bottom two of
another in a single result?
Parenthesise each branch with its own ORDER BY and LIMIT, then combine with
UNION ALL and apply a final ORDER BY to the whole thing.
6. Where would you use UNION ALL in a production schema design?
Across a hot and an archived table of the same shape, usually behind a view, so
reads span both without the application knowing. ALL is correct there because
the partitions are disjoint by construction.
Next
That closes Part 1. Group by and having opens Part 2, where the rows start collapsing into groups.