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 54/ 160
03. Joins & Relational Querying

Semi-Joins & Anti-Joins (EXISTS, NOT EXISTS, IN, NOT IN Pitfalls with NULL)

Express existence checks safely and avoid NOT IN + NULL traps.

IntermediateEXISTS · NOT EXISTS · NULL3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

EXISTS asks "is there at least one match?" and NOT EXISTS asks "is there no match at all?". You get the original rows back, once each.

Think of it like…

Semi-join: "list the students who handed in at least one assignment"; you don't care how many. Anti-join: "list the students who handed in nothing".

Where you’ve seen it

A win-back campaign targets customers with no order in 90 days: SELECT c.* FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id AND o.created_at > now() - interval '90 days').

Words you’ll hear

Semi-join
Rows with at least one match: EXISTS or IN.
Anti-join
Rows with no match: NOT EXISTS or LEFT JOIN … IS NULL.
Correlated subquery
A subquery that refers to the outer row, as in o.customer_id = c.id.
NOT IN NULL trap
x NOT IN (…, NULL) is never TRUE, so the query returns no rows.

Visual diagram

Loading interactive diagram

Theory & example queries

Semi-joins: EXISTS vs IN vs JOIN

EXISTS can stop as soon as it finds one match, and each outer row appears at most once. IN (subquery) has the same meaning, and modern optimizers usually produce the same plan for both.

An INNER JOIN is not a semi-join: a customer with 10 orders appears 10 times. Adding DISTINCT hides the duplicates, but the database still builds the larger result and then deduplicates it.

Customers who ordered at least onceQuery example
1Input dataStart from the source rows or state that the statement sees.
customers
3 rows
customers sample rows
idnameemailcity
1Mayamaya@example.comPune
2Raviravi@example.comDelhi
3Noornoor@example.comMumbai
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  c.*3FROM4  customers c5WHERE6  EXISTS (7    SELECT8      19    FROM10      orders o11    WHERE12      o.customer_id = c.id13  );
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/13
3OutputInspect the representative rows, affected-row count, plan, or command status.
Customers with at least one order2 sample rows
Customers with at least one order
idnamecity
1AshaPune
3KabirDelhi

Note: Assumes these are the only sample customers with matching orders; columns reflect an illustrative customers table.

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

Key takeaway: For "has at least one", use EXISTS, not JOIN + DISTINCT.

Anti-joins and the NOT IN trap

WHERE id NOT IN (SELECT customer_id FROM orders) means id <> a AND id <> b AND id <> NULL …. The comparison with NULL is UNKNOWN, so the whole condition is never TRUE and the query returns zero rows.

NOT EXISTS doesn't have this problem because it only asks whether a matching row exists. LEFT JOIN … WHERE o.id IS NULL also works, as long as you test a column that is never NULL on real matches, such as the primary key.

A safe anti-joinQuery example
1Input dataStart from the source rows or state that the statement sees.
customers
3 rows
customers sample rows
idnameemailcity
1Mayamaya@example.comPune
2Raviravi@example.comDelhi
3Noornoor@example.comMumbai
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  c.*3FROM4  customers c5WHERE6  NOT EXISTS (7    SELECT8      19    FROM10      orders o11    WHERE12      o.customer_id = c.id13  );
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/13
3OutputInspect the representative rows, affected-row count, plan, or command status.
Customers with no orders2 sample rows
Customers with no orders
idnamecity
2LeenaJaipur
4MinaPune

Note: Assumes these sample customers have no matching row in orders.

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

Key takeaway: Default to NOT EXISTS for "has no match".

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 1Question

Has a match, or has none?

"Customers who ordered" is a semi-join; "customers who never ordered" is an anti-join. Neither needs columns from orders.

Focus at this step

EXISTS vs NOT EXISTS

What to watch at this step
Columns from right table
none
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

A semi-join returns rows from one table that have *at least one* match in another (EXISTS, IN). An anti-join returns rows that have *no* match (NOT EXISTS, LEFT JOIN … IS NULL, NOT IN). Neither adds columns from the other table or duplicates rows.

Why it matters: "Users who placed an order" and "users who never did" are among the most common interview and analytics questions. The trap is NOT IN: a single NULL in the subquery makes it return nothing.

When to reach for it

  • Finding users who never converted, churned, or have no profile
  • Filtering to entities that have at least one related event
  • Data quality checks, such as orders whose customer no longer exists

When to avoid or be careful

  • NOT IN against a nullable column
  • INNER JOIN + DISTINCT when you only need to know a match exists
  • Putting the time-window filter outside the subquery, which changes the meaning

Ways to write "customers with no orders"

NOT EXISTS
Best for: The default anti-join

Strengths: NULL-safe, clear intent, planned as an anti-join.

Watch out: Slightly more typing.

LEFT JOIN … WHERE o.id IS NULL
Best for: When you also want to look at joined columns while debugging

Strengths: Works everywhere and usually gets the same plan.

Watch out: You must test a non-nullable column, and extra WHERE conditions easily break it.

NOT IN (subquery)
Best for: Only when the subquery column is guaranteed NOT NULL

Strengths: Reads naturally.

Watch out: Returns no rows at all if the subquery contains a NULL.

Interview signals & numbers to know

When this topic comes up

  • “Customers who never placed an order”
  • “Users with at least one purchase”
  • NOT IN returns nothing
  • EXISTS vs IN
  • A JOIN produces duplicate rows

Benchmarks & rules of thumb

1 -
match is enough for EXISTS to stop
1 NULL -
is enough to break NOT IN
0 -
extra rows added by a semi-join

Common mistakes & follow-ups

Common interview mistakes

  • Using NOT IN when the subquery column contains NULLs.
  • Using a JOIN for an existence check and then patching the duplicates with DISTINCT.
  • In the LEFT JOIN version, testing IS NULL on a column that can legitimately be NULL.

Likely interviewer follow-ups

  • Why does NOT IN behave differently from NOT EXISTS when NULLs are present?
  • Is IN faster than EXISTS? What does the optimizer actually do?
  • How would you find products that weren't ordered in the last 30 days?
Interview tip: Answer with NOT EXISTS, mention LEFT JOIN … IS NULL as an equivalent, then explain why you avoid NOT IN. The NULL explanation is what interviewers listen for.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Semi-Joins & Anti-Joins (EXISTS, NOT EXISTS, IN, NOT IN Pitfalls with NULL) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Join Explosion / Fan-Out Bugs & How to Prevent Duplicate Counts
Next topic
LATERAL Joins (Correlated Subqueries in the FROM Clause)