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

Finding Missing Records (LEFT JOIN ... WHERE right.id IS NULL)

Detect orphans and gaps with anti-join patterns using LEFT JOIN + IS NULL.

IntermediateAnti-Join Pattern · IS NULL Filter3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Match everything you can, then look at what's left with no partner.

Think of it like…

Taking the register against a class list: go down the list and put a tick next to each student who turns up; the names with no tick are the ones missing.

Where you’ve seen it

A nightly data-quality job checks that every paid order reached the warehouse: SELECT s.order_id FROM source_orders s LEFT JOIN dw.fact_orders f ON f.order_id = s.order_id WHERE s.status = 'paid' AND s.paid_at::date = current_date - 1 AND f.order_id IS NULL; Any rows returned trigger an alert before the morning revenue report goes out.

Words you’ll hear

Anti-join
Keeping rows of one table that have no match in another.
Orphan row
A child row whose parent (for example its customer) doesn't exist.
IS NULL on the join key
The reliable test: the right table's key is only NULL when no row matched.
Reconciliation
Comparing two sources of the same data to find what's missing on either side.

Visual diagram

Loading interactive diagram

Theory & example queries

Writing the pattern correctly

After a LEFT JOIN, a left row with no partner gets NULL in every right-side column. Test a right-side column that can never be NULL in a real match, normally its primary key or the join column: WHERE o.id IS NULL. If you test a nullable column such as o.coupon_code, you'll also get customers whose orders simply have no coupon.

Conditions on the right table must go in the ON clause. "Customers with no orders this year" is LEFT JOIN orders o ON o.customer_id = c.id AND o.created_at >= '2026-01-01' WHERE o.id IS NULL. Putting the date in WHERE instead removes the NULL rows before IS NULL is checked, and the query returns nothing. NOT EXISTS expresses the same thing and most planners produce the same anti-join plan, so use whichever reads better.

Products never sold in NovemberQuery example
1Input dataStart from the source rows or state that the statement sees.
order_items
3 rows
order_items sample rows
idorder_idproduct_idqtyprice
110142249.5
2101841150
310242149.5
products
3 rows
products sample rows
idnamepricecategorystock
42SQL Notebook49.5books18
84Mechanical Keyboard150hardware5
11Query Mug12.99gifts33
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  p.id,3  p.name4FROM5  products p6  LEFT JOIN order_items oi ON oi.product_id = p.id7  AND oi.created_at >= '2026-11-01'8  AND oi.created_at < '2026-12-01'9WHERE10  oi.order_id IS NULL;
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/10
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output3 sample rows
Expected output
idname
18Canvas Tote
27Desk Calendar
41Travel Mug

Note: Illustrative products with no matching order item during November 2026.

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

Key takeaway: IS NULL on the right table's key; right-table conditions in ON.

Orphans, expected records and two-way diffs

Three common uses. Orphans: child rows pointing at missing parents, which appear when there's no foreign key or data was loaded around it; join child to parent and keep parent.id IS NULL. Expected but missing: every active subscription should have an invoice this month, so LEFT JOIN subscriptions to this month's invoices. Missing dates: join a date spine to the events table to find days with no data at all.

To compare two copies of a dataset in both directions, use FULL OUTER JOIN and keep rows where either side is NULL: SELECT COALESCE(a.id, b.id) AS id, a.id IS NULL AS missing_in_a, b.id IS NULL AS missing_in_b FROM system_a a FULL JOIN system_b b ON b.id = a.id WHERE a.id IS NULL OR b.id IS NULL; On large tables, index the join columns on both sides, or the check becomes a pair of full scans plus a hash join.

Invoices missing for active subscriptionsQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  s.id3FROM4  subscriptions s5  LEFT JOIN invoices i ON i.subscription_id = s.id6  AND i.period = '2026-11'7WHERE8  s.status = 'active'9  AND i.id IS NULL;
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/9
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output3 sample rows
Expected output
id
204
311
907

Note: Illustrative active subscriptions missing a November 2026 invoice.

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

Here s.status is in WHERE because it filters the left table.

Key takeaway: Left-table filters in WHERE, right-table filters in ON; FULL JOIN for two-way diffs.

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

Decide which side must exist

Put the table whose rows you want to report on the left: customers for "customers without orders", orders for "orders without customers".

SQL at this step
1FROM2  customers c3  LEFT JOIN orders o
What to watch at this step
Left
what you report
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

To find rows in one table with no match in another, LEFT JOIN them and keep the rows where the right side came back empty: SELECT o.* FROM orders o LEFT JOIN customers c ON c.id = o.customer_id WHERE c.id IS NULL; returns orders whose customer doesn't exist, often called orphans. The same pattern finds customers with no orders, products never sold, and records that exist in one system but not another.

Why it matters: Most data-quality checks are "what's missing?" questions: payments without an invoice, events from deleted users, rows that didn't make it from the source into the warehouse. Interviewers ask for this pattern directly, and they watch for the two classic mistakes: testing the wrong column for NULL, and filtering the right table in WHERE.

When to reach for it

  • Customers, products or users with no activity
  • Orphaned child rows and broken references
  • Checking a load or migration copied everything

When to avoid or be careful

  • Testing a nullable right-side column for IS NULL
  • Filtering the right table in WHERE
  • Running reconciliation joins on unindexed columns of big tables

LEFT JOIN … IS NULL vs NOT EXISTS vs NOT IN

LEFT JOIN … WHERE right.id IS NULL
Best for: When you also want columns from a partial match or a two-way diff

Strengths: Familiar; easy to switch into a FULL JOIN reconciliation.

Watch out: Easy to break with a right-side filter in WHERE.

NOT EXISTS
Best for: Plain "has no matching row" checks

Strengths: States the intent directly; NULL-safe.

Watch out: Can't return columns from the other table.

NOT IN (subquery)
Best for: Short constant lists

Strengths: Short to write.

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

Interview signals & numbers to know

When this topic comes up

  • “Customers who never placed an order”
  • “Find orphaned records”
  • “Which rows didn't make it into the warehouse?”
  • Data-quality checks
  • LEFT JOIN with IS NULL

Benchmarks & rules of thumb

0 rows -
the expected result of a healthy orphan check
2 -
places a condition can go: ON or WHERE
1 NULL -
enough to empty a NOT IN result

Common mistakes & follow-ups

Common interview mistakes

  • Writing WHERE o.created_at >= '2026-01-01' AND o.id IS NULL and getting zero rows every time.
  • Checking o.discount_code IS NULL and counting customers whose orders had no discount as having no orders.
  • Running the orphan check once instead of scheduling it, so new orphans go unnoticed.

Likely interviewer follow-ups

  • Find customers who signed up but never placed an order.
  • How would you check every row in a source table reached the warehouse?
  • Why does moving a condition from ON to WHERE change the result?
Interview tip: Write the query, then point out where the date filter goes and which column you test for NULL. Explaining those two choices is what separates a confident answer.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Finding Missing Records (LEFT JOIN ... WHERE right.id IS NULL) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
LEFT JOIN (Left Outer Join) & Preserving Unmatched Rows
Next topic
RIGHT JOIN & When to Rewrite as LEFT JOIN