NO. 11 · 7 exercises

11. Set Operations

UNION, INTERSECT, EXCEPT — stacking result sets.

The lesson

Set Operations

Every year the store highlights ten titles on a wall display, and each year's list lives in its own table: featured_2023 and featured_2024. Two lists, and the questions write themselves: Which titles were featured either year? Which both years? Which only in 2023?

Answering those with plain WHERE is awkward — the two tables have nothing to join on, they're just two columns of titles. Instead of joining rows sideways, set operations combine result sets vertically: one query's rows stacked over another's, or subtracted from it. There are four operators, and once you see the first, the rest are variations.

The two lists

featured_2023featured_2024
Golden HourGolden Hour
Mar AdentroLas Luces
Meridian BlueMeridian Blue
King DeltaPaper Wings
Neon DistrictNeon District
Winter LightStatic & Honey
Rivers RunDesde Dentro
Desde DentroNocturne No. 1
Fjord SongsSparrows
Corazón de SalMaré

Ten titles each, and four appear in both: Golden Hour, Meridian Blue, Neon District and Desde Dentro. Every operator below is a different way of slicing these two lists.

UNION: everything, once

SELECT title FROM featured_2023
UNION
SELECT title FROM featured_2024;

Sixteen rows come back: all twenty titles, with the four overlaps collapsed into one row each. UNION stacks the two result sets and removes duplicate rows — it's SELECT DISTINCT applied to the combined output.

Three rules govern every set operation:

  • Both queries must return the same number of columns.
  • Column names come from the first query (aliases in the second are ignored).
  • Duplicate rows are removed across the whole result — which is why the four shared titles appear exactly once.

UNION ALL: keep everything

Inventory wants the raw count — duplicates included:

SELECT title FROM featured_2023
UNION ALL
SELECT title FROM featured_2024;

Twenty rows. ALL means "don't bother de-duplicating". It's also faster for the database, and when the lists can't overlap, it's the polite choice.

INTERSECT: in both

SELECT title FROM featured_2023
INTERSECT
SELECT title FROM featured_2024;

INTERSECT keeps only the rows present in both result sets: four titles — the titles that made the wall two years running.

EXCEPT: in one but not the other

SELECT title FROM featured_2023
EXCEPT
SELECT title FROM featured_2024;

Six titles: everything the 2023 wall had that the 2024 wall doesn't — Mar Adentro, King Delta, Winter Light, Rivers Run, Fjord Songs and Corazón de Sal.

The order of the operands is the question. Flip the tables and you get a different answer:

SELECT title FROM featured_2024
EXCEPT
SELECT title FROM featured_2023;

The six titles that joined the wall in 2024: Las Luces, Paper Wings, Static & Honey, Nocturne No. 1, Sparrows and Maré. A EXCEPT B and B EXCEPT A are mirror images — read the operands carefully.

Labelling the lists

Set operations compare whole rows, not single columns. That's a feature: give each title a year label and the overlaps stop colliding, because ('Golden Hour', 2023) and ('Golden Hour', 2024) are different rows.

SELECT title, '2023' AS list_year FROM featured_2023
UNION
SELECT title, '2024' AS list_year FROM featured_2024;

Twenty rows come back: each shared title appears twice, once per year, and list_year says which year it was. Literals work as columns anywhere, and here they turn two bare lists into one small catalog.

ORDER BY and parentheses

ORDER BY in a set operation goes once, at the very end — it sorts the combined result, and it's a clause of the whole operation, not of either branch:

SELECT title FROM featured_2023
EXCEPT
SELECT title FROM featured_2024
ORDER BY title;

Same six rows, now in alphabetical order.

Mixed operations need parentheses. The curator wants the titles featured in exactly one year — the symmetric difference:

SELECT title FROM (SELECT title FROM featured_2023 EXCEPT SELECT title FROM featured_2024)
UNION
SELECT title FROM (SELECT title FROM featured_2024 EXCEPT SELECT title FROM featured_2023);

Twelve rows: the six from each one-year-only list. Each EXCEPT is wrapped in parentheses so the UNION sees two complete results. Leave the parentheses out and SQLite evaluates the operators left to right — the first EXCEPT would swallow titles that the second then has to give back, and you'd silently get six rows instead of twelve.

What you just learned

  • Set operations stack result sets vertically: UNION (deduplicated) and UNION ALL (everything).
  • INTERSECT keeps rows present in both; EXCEPT keeps rows in the first but not the second — and the operands' order matters.
  • Both queries must return the same number of columns; names and types come from the first query.
  • Whole rows are compared, so an added label column stops shared titles from colliding.
  • One ORDER BY at the very end sorts everything; parentheses group mixed operations.

Dialect note. SQLite, PostgreSQL and SQL Server all call the set-difference operator EXCEPT; Oracle and older MySQL versions call it MINUS. Precedence also differs: SQLite evaluates UNION / INTERSECT / EXCEPT strictly left to right, while standard SQL gives INTERSECT priority — so with mixed operators, always parenthesize rather than trust the engine.

The last exercise of this chapter is the symmetric difference you just built. Everything else was a warm-up for that one query.