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

Filtering in ON Clause vs WHERE Clause in Outer Joins

Put predicates in ON vs WHERE correctly so outer joins stay outer.

IntermediateON Filters · WHERE Filters3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

ON says how to match rows. WHERE throws rows away after matching. Put conditions about the optional table in ON if you want to keep everyone.

Think of it like…

Inviting every employee to a lunch (LEFT JOIN) and noting who's vegetarian. ON is the rule for pairing people with meal choices. WHERE is a bouncer at the door afterwards: tell him "only vegetarians" and everyone without a recorded choice gets turned away too.

Where you’ve seen it

"Every customer with their November orders, including customers with none": FROM customers c LEFT JOIN orders o ON o.customer_id = c.id AND o.created_at >= '2026-11-01' keeps everyone. Moving the date condition to WHERE drops every customer without a November order.

Words you’ll hear

ON condition
Decides which right rows pair with each left row.
WHERE condition
Filters rows after the join is built.
Preserved table
The side an outer join keeps in full (the left table in LEFT JOIN).
Null-rejecting filter
A WHERE condition that's never true for NULL, which removes NULL-padded rows.

Visual diagram

Loading interactive diagram

Theory & example queries

Right-table conditions: ON keeps, WHERE removes

A LEFT JOIN first pairs each left row with right rows that satisfy ON, padding with NULLs when none do. WHERE then filters that result. A WHERE condition on a right-table column, like o.status = 'paid', evaluates to UNKNOWN on NULL-padded rows, so those rows (the customers with no paid orders) are removed.

Put the condition in ON and it only restricts which orders can match: customers without paid orders still appear, with NULL order columns. The one deliberate use of a right-table condition in WHERE is the anti-join, WHERE o.id IS NULL, which keeps exactly the unmatched rows.

Customers with their paid-order count, including zeroQuery 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.id,3  COUNT(o.id)4FROM5  customers c6  LEFT JOIN orders o ON o.customer_id = c.id7  AND o.status = 'paid'8GROUP BY9  c.id;
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.
Representative paid-order counts3 sample rows
Representative paid-order counts
idcount
72
80
91

Note: Sample data assumes customer 8 has no paid order; the LEFT JOIN still preserves that customer and COUNT(o.id) returns zero.

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

Key takeaway: Filter the optional (right) side in ON.

Left-table conditions, and chains of joins

The reverse surprise: a left-table condition in ON, such as ON o.customer_id = c.id AND c.country = 'IN', doesn't remove non-Indian customers. They're still returned, just without any matched orders, because a LEFT JOIN keeps every left row no matter what ON says. To filter the left table, use WHERE.

In multi-join queries, an INNER JOIN (or a WHERE filter) on a table that was LEFT-joined earlier also discards the NULL-padded rows, undoing the outer join. Either make the later joins LEFT JOINs too, or group the optional tables with parentheses or a subquery.

Filter left rows in WHERE, right rows in ONQuery 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.id,3  o.id4FROM5  customers c6  LEFT JOIN orders o ON o.customer_id = c.id7  AND o.status = 'paid'8WHERE9  c.country = 'IN';
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.
Representative Indian customers3 sample rows
Representative Indian customers
c.ido.id
7901
7908
8NULL

Note: Sample data assumes two paid orders for customer 7 and no paid order for Indian customer 8. The qualified labels distinguish the two id columns; an unaliased client may display both with the label id.

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

Key takeaway: Left-table filters → WHERE; right-table filters → ON.

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

Name the preserved table

Decide which table's rows must all appear. That's the left table of the LEFT JOIN.

Focus at this step

keep every customer

What to watch at this step
Preserved
left table
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

In an outer join, ON decides which rows *match*, while WHERE decides which rows of the *joined result* survive. For a LEFT JOIN, every left row is kept regardless of ON; a condition on the right table in WHERE then removes the rows where that side is NULL, silently turning the LEFT JOIN into an INNER JOIN. For inner joins, ON and WHERE give the same result.

Why it matters: It's the most common outer-join bug in real code, and a favourite interview trick question: two queries that look nearly identical return different row counts. The subtler half, that a *left*-table condition in ON doesn't filter the left table at all, catches even experienced developers.

When to reach for it

  • Reports that must show zero values for entities without activity
  • Restricting matches to a date range or status
  • Debugging "rows disappeared after I added a filter"

When to avoid or be careful

  • Right-table conditions in WHERE (except IS NULL anti-joins)
  • Left-table conditions in ON when you meant to filter
  • INNER JOINs after a LEFT JOIN that silently drop NULL-padded rows

Where a condition goes in a LEFT JOIN

Right-table condition in ON
Best for: Filtering which related rows count, while keeping every left row

Strengths: Preserves the outer join.

Watch out: Easy to forget when refactoring.

Right-table condition in WHERE
Best for: Only the anti-join check (right.id IS NULL)

Strengths: Clear way to find rows with no match.

Watch out: Any other condition turns the join into an inner join.

Left-table condition in WHERE
Best for: Choosing which left rows appear

Strengths: Filters the preserved table as intended.

Watch out: None; in ON it would have no filtering effect.

Interview signals & numbers to know

When this topic comes up

  • “My LEFT JOIN behaves like an INNER JOIN”
  • “Customers with zero orders are missing”
  • “ON vs WHERE in outer joins”
  • Counts drop after adding a filter
  • Multi-table outer joins

Benchmarks & rules of thumb

All left rows -
kept by LEFT JOIN regardless of ON
0 -
difference between ON and WHERE for inner joins
IS NULL -
the one right-table WHERE filter that keeps the anti-join

Common mistakes & follow-ups

Common interview mistakes

  • Adding WHERE o.status = 'paid' and losing every customer without a paid order.
  • Writing ON … AND c.active = true and expecting inactive customers to disappear.
  • Following a LEFT JOIN with an INNER JOIN to a child of the right table, dropping unmatched rows again.

Likely interviewer follow-ups

  • Why does a WHERE condition on the right table turn a LEFT JOIN into an INNER JOIN?
  • What happens if you put a left-table condition in the ON clause of a LEFT JOIN?
  • Are ON and WHERE interchangeable for INNER JOINs?
Interview tip: Show the paid-orders example both ways with row counts (100 vs 60), then mention the left-table-in-ON surprise. Covering both directions is what impresses interviewers.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Filtering in ON Clause vs WHERE Clause in Outer Joins with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
NATURAL JOIN & USING Clause (and Why to Avoid NATURAL JOIN)
Next topic
Join Explosion / Fan-Out Bugs & How to Prevent Duplicate Counts