skipnothing/SQL

UNION, INTERSECT, EXCEPT

Two buyers placed three orders in January, two ordered in February, and one shows up in both months. Asking for everyone, only the repeat buyers, or only the January-only crowd is the same two SELECT results stacked three different ways.

  • ▸Three January order-rows over two February ones give five rows raw, but only three distinct buyers once duplicates collapse.
  • ▸One buyer ordered in both months; subtracting one query from the other flips its answer when you swap the operands.
  • ▸Stacked queries align columns by position, not name, so a reordered select list quietly files amounts under user_id.
BUILDS ON
01

Stacking Results, Not Widening Rows

A query that asks SELECT user_id FROM orders WHERE created_at >= '2026-01-01' AND created_at < '2026-02-01' hands back a short list of January's buyers: user 1, user 1, user 2. Shift the dates to February and a second query hands back its own list: user 1, user 3. Two results, each a single user_id column.

Every join so far made each row *wider*, gluing a partner's columns onto the side. Combining these two lists is a different move: it makes the result *taller*, setting the second list's rows directly beneath the first. Nothing pairs up; the rows simply pile on.

For that pile to make sense, the two results have to line up: the same number of columns, comparable types, read left to right. Here each result is a single user_id column, so they stack cleanly into one taller list of buyers. Comparable is not the same as meaningful: stacking February's amount under January's user_id runs, and files 8.00 and 30.00 under the user_id header. Rows-beside-rows from a join and rows-below-rows from this stack are the two ways to put two query results together, and the rest of this topic is about controlling exactly which rows survive the stack.

TWO RESULTS, STACKED INTO ONE

Keep going, sign up to unlock the rest

4 more parts in this topic, plus 30+ more topics in SQL.

Sign up, it's freeSee the full SQL