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):
SELECT name, 'student' AS role FROM studentsUNION ALLSELECT name, 'mentor' AS role FROM mentors;-- All people with a role label.SELECT city FROM studentsUNION -- distinct cities across both tablesSELECT city FROM mentors;
INTERSECT & EXCEPT
-- Rows in BOTH queriesSELECT customer_id FROM orders_janINTERSECTSELECT customer_id FROM orders_feb; -- bought in both months-- Rows in the first but NOT the secondSELECT product_id FROM sold_2025EXCEPTSELECT 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 BYat 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
- 01Set operations stack rows from two queries (JOINs add columns).
- 02UNION removes duplicates; UNION ALL keeps them and is faster.
- 03INTERSECT returns rows in both queries; EXCEPT returns rows in the first but not the second.
- 04Both queries need the same column count/order and compatible types; names come from the first.
- 05JOIN combines columns of related tables; set ops combine rows of similar queries.
