Code of the Day
IntermediateCombining data

Set operations

Stack the rows of two queries with UNION, INTERSECT, and EXCEPT.

SQLIntermediate7 min read
Recommended first
By the end of this lesson you will be able to:
  • Combine query results with UNION (and UNION ALL)
  • Know INTERSECT and EXCEPT
  • Understand the column-compatibility rule

Joins combine tables side by side (more columns). stack results top to bottom (more rows) — they take two queries and combine their row sets.

UNION

UNION returns the rows from both queries, removing duplicates. The two queries must produce the same number of columns, in compatible types:

SQL — editable, runs in your browser

Use UNION ALL to keep duplicates — it's also faster, since it skips the de-duplication step. Reach for UNION ALL unless you specifically need uniques.

INTERSECT and EXCEPT

Two more, both also requiring matching columns:

  • INTERSECT — rows present in both queries.
  • EXCEPT — rows in the first query but not the second (a set difference).
SELECT product_id FROM order_items WHERE order_id = 1
EXCEPT
SELECT product_id FROM order_items WHERE order_id = 3;

That's "products on order 1 but not on order 3."

The column-count/type rule is the whole catch: SELECT name and SELECT id, name can't be UNIONed. Line the columns up first.

Where to go next

Last in the module: views — saving a query under a name to reuse it.

Finished reading? Mark it complete to track your progress.

On this page