Skip to main content
Albero Academy

Set Operations

Combine the results of two queries — UNION, UNION ALL, INTERSECT and EXCEPT — and when to reach for each versus a JOIN.

Chapter 12SQL13 min readBeginner friendly
  • #SQL
  • #UNION
  • #Set Operations

Joins combine tables side by side (adding columns); set operations stack query results on top of each other (adding rows). They answer questions like "everyone who is a student or a mentor", "customers who bought in both months", or "products that sold last year but not this year".

UNION & UNION ALL

UNION combines the rows of two queries and removes duplicates; UNION ALL keeps them all (and is faster because it skips the de-duplication):

stacking results
SELECT name, 'student' AS role FROM students
UNION ALL
SELECT name, 'mentor' AS role FROM mentors;
-- All people with a role label.
SELECT city FROM students
UNION -- distinct cities across both tables
SELECT city FROM mentors;

INTERSECT & EXCEPT

common & difference
-- Rows in BOTH queries
SELECT customer_id FROM orders_jan
INTERSECT
SELECT customer_id FROM orders_feb; -- bought in both months
-- Rows in the first but NOT the second
SELECT product_id FROM sold_2025
EXCEPT
SELECT product_id FROM sold_2026; -- sold in 2025 but not 2026

The rules

  • Both queries must return the same number of columns, in the same order, with compatible types.
  • Column names come from the first query.
  • A single ORDER BY at the very end sorts the combined result.

Set ops vs JOIN

Reach for a JOIN to combine columns from related tables (a student and their programme). Reach for a set operation to combine rows from similarly-shaped queries. Many "both / either / neither" questions are cleanest as set operations.

Practice

Build a single list of all people (students UNION ALL mentors) with a role column. Find customers who appear in two monthly order tables (INTERSECT), and products present last year but missing this year (EXCEPT).

Key takeaways

  1. 01Set operations stack rows from two queries (JOINs add columns).
  2. 02UNION removes duplicates; UNION ALL keeps them and is faster.
  3. 03INTERSECT returns rows in both queries; EXCEPT returns rows in the first but not the second.
  4. 04Both queries need the same column count/order and compatible types; names come from the first.
  5. 05JOIN combines columns of related tables; set ops combine rows of similar queries.