INTERSECT & EXCEPT (Set Differences)
Isolate shared records with INTERSECT and compute set differences with EXCEPT or MINUS.
INTERSECT & EXCEPT (Set Differences) is an essential topic in SQL and relational database engineering.
Overview
Building on foundational principles introduced in sql-union, mastering intersect & except (set differences) provides the core mental model and practical query skills needed for production relational database engineering.
-- Find customers who bought items in both 2024 and 2025
SELECT customer_id FROM orders_2024
INTERSECT
SELECT customer_id FROM orders_2025;
-- Find customers who bought in 2024 but NEVER in 2025
SELECT customer_id FROM orders_2024
EXCEPT
SELECT customer_id FROM orders_2025;
Key Concepts
- Understand the fundamental syntax, conventions, and mental model.
- Avoid common beginner traps, data type mismatches, and performance pitfalls.
- Apply practical idioms directly in production applications.
[!TIP] Master this concept to build a rock-solid foundation. Next, proceed to subqueries-basics.