Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 39/ 160
02. Aggregations, Functions & Data Manipulation

Set Differences & Intersections (INTERSECT, EXCEPT)

Find shared or missing rows between queries with INTERSECT and EXCEPT.

IntermediateINTERSECT · EXCEPT3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

INTERSECT keeps what both lists share. EXCEPT keeps what's in the first list but not the second.

Think of it like…

Two guest lists: INTERSECT is the people on both lists; EXCEPT is the people on the first list who aren't on the second.

Where you’ve seen it

Checking a migration copied a table exactly: (SELECT * FROM orders_old EXCEPT SELECT * FROM orders_new) UNION ALL (SELECT * FROM orders_new EXCEPT SELECT * FROM orders_old);. Zero rows means the two tables hold the same rows (ignoring duplicates).

Words you’ll hear

INTERSECT
Rows present in both results.
EXCEPT / MINUS
Rows in the first result but not in the second.
ALL variants
INTERSECT ALL and EXCEPT ALL keep duplicate counts (PostgreSQL).
Whole-row comparison
Every selected column must match, and NULL equals NULL.

Visual diagram

Loading interactive diagram

Theory & example queries

How they behave

Both queries must return the same number of columns with compatible types, matched by position. INTERSECT keeps rows found in both; EXCEPT keeps rows from the left that have no identical row on the right. By default both remove duplicates; PostgreSQL's INTERSECT ALL and EXCEPT ALL keep multiplicity (if A has a row 3 times and B twice, A EXCEPT ALL B returns it once).

Set operations compare whole rows and consider two NULLs equal, which joins don't (NULL = NULL is never true in ON). That makes EXCEPT a convenient, NULL-safe way to diff two tables with identical shapes. In standard SQL, INTERSECT binds more tightly than UNION and EXCEPT, so use parentheses when combining them.

Users who bought in both monthsQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  user_id3FROM4  orders5WHERE6  created_at >= '2026-10-01'7  AND created_at < '2026-11-01'8INTERSECT9SELECT10  user_id11FROM12  orders13WHERE14  created_at >= '2026-11-01'15  AND created_at < '2026-12-01';
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/15
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative repeat purchasers3 sample rows
Representative repeat purchasers
user_id
17
42
91

Note: Assumes these users placed at least one order in both October and November 2026; INTERSECT removes duplicate user_id values.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Positional, whole-row, duplicate-removing, NULL-equal.

Set operations vs EXISTS and joins

EXCEPT and NOT EXISTS can answer the same question, but they compare different things. EXCEPT compares every selected column, so to find users who bought in October but not November you select only user_id on both sides. NOT EXISTS compares on chosen keys and can still return other columns from the outer table, such as the user's name and email.

Use set operations for clean list comparisons and table diffs. Use EXISTS / NOT EXISTS (or joins) when you need extra columns, partial matching on some keys, or when the planner handles them better on large data. MySQL supports INTERSECT and EXCEPT only from 8.0.31; before that, use joins or EXISTS.

Same question, returning more columnsQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
users
3 rows
users sample rows
idcountrycitysignup_date
1INPune2026-10-01
2INDelhi2026-10-02
3NULLMumbai2026-10-03
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  u.id,3  u.email4FROM5  users u6WHERE7  EXISTS (8    SELECT9      110    FROM11      orders o12    WHERE13      o.user_id = u.id14      AND o.created_at >= '2026-10-01'15      AND o.created_at < '2026-11-01'16  )17  AND NOT EXISTS (18    SELECT19      120    FROM21      orders o22    WHERE23      o.user_id = u.id24      AND o.created_at >= '2026-11-01'25  );
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/25
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative October-only purchasers2 sample rows
Representative October-only purchasers
idemail
23asha@example.com
68kabir@example.com

Note: Illustrative users with an October order and no November order. The upper date bound in the NOT EXISTS intentionally matches the example.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Set operations for list comparisons; EXISTS when you need other columns or key-based matching.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Inputs

Build two comparable queries

Select exactly the columns that define "the same row", in the same order and types, on both sides.

SQL at this stepReadable preview
1SELECT user_id … /2SELECT user_id …
What to watch at this step
Match by
position
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

INTERSECT returns rows that appear in both queries' results; EXCEPT returns rows from the first query that don't appear in the second (Oracle calls it MINUS). Like UNION, they match columns by position and remove duplicates by default. Unlike joins, they compare whole rows and treat NULLs as equal.

Why it matters: They're the most direct way to compare two datasets: what's in both lists, what's missing from one, or whether two versions of a table differ at all. They're also a quick answer to "users who did X and Y" questions, and interviewers like to compare them with EXISTS and joins.

When to reach for it

  • Verifying data migrations and backfills
  • Users who did X and Y, or X but not Y
  • Finding rows missing from one system

When to avoid or be careful

  • Selecting extra columns that make otherwise matching rows look different
  • Assuming EXCEPT keeps duplicates
  • Using INTERSECT/EXCEPT on MySQL versions before 8.0.31

EXCEPT vs NOT EXISTS vs LEFT JOIN … IS NULL

EXCEPT
Best for: Comparing two lists or table versions with the same shape

Strengths: Short, NULL-safe, compares whole rows.

Watch out: Returns only the compared columns; deduplicates.

NOT EXISTS
Best for: Rows without a match on chosen keys, with extra columns

Strengths: Flexible matching; returns any columns of the outer table.

Watch out: More verbose.

LEFT JOIN … WHERE right.key IS NULL
Best for: Anti-joins in engines with weak set-operation support

Strengths: Works everywhere.

Watch out: Easy to break with extra WHERE conditions; NULL keys never match.

Interview signals & numbers to know

When this topic comes up

  • “Users who bought in both months”
  • “What's in table A but not table B?”
  • “Did the migration copy everything?”
  • Set operations
  • MINUS in Oracle code

Benchmarks & rules of thumb

2 -
directions needed for a full table diff
NULL = NULL -
treated as equal by set operations
MySQL 8.0.31 -
INTERSECT and EXCEPT added

Common mistakes & follow-ups

Common interview mistakes

  • Including a timestamp column in both queries, so no rows ever match.
  • Writing B EXCEPT A when you meant A EXCEPT B.
  • Checking only one direction of a table diff and missing rows added to the new table.

Likely interviewer follow-ups

  • How would you check whether two tables contain exactly the same rows?
  • When would you use NOT EXISTS instead of EXCEPT?
  • How do INTERSECT and EXCEPT treat NULL values?
Interview tip: Use the October/November buyers example: INTERSECT for repeat buyers, EXCEPT both ways for churned and new. Then add the two-direction table diff, which is a practical trick interviewers like.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Set Differences & Intersections (INTERSECT, EXCEPT) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Set Operations (UNION vs UNION ALL)
Next topic
Writing Clean, Readable & Maintainable SQL Style Guides