0PricingLogin
SQL Interview Prep · Lesson

INTERSECT and EXCEPT for Comparison

Finding common and differing rows between two datasets.

The Comparison Operators

INTERSECT and EXCEPT are the set operators for comparing two result sets rather than merging them. Interviewers reach for them in questions like "which customers are in both lists" or "which rows are in A but not B".

  • INTERSECT = rows present in both queries.
  • EXCEPT = rows in the first query but not the second.

What INTERSECT Returns

INTERSECT returns only the distinct rows that appear in both result sets. A row must match on every column to count as common.

Like UNION, plain INTERSECT removes duplicates, returning each common row once.

SELECT customer_id FROM orders_2023
INTERSECT
SELECT customer_id FROM orders_2024;
-- customers who ordered in BOTH years

All lessons in this course

  1. UNION vs UNION ALL
  2. Column Count and Type Compatibility
  3. INTERSECT and EXCEPT for Comparison
  4. Emulating Set Operations With Joins
← Back to SQL Interview Prep