Explain it simply
Explain it simply
Picture a teacher holding the full class list and writing homework scores next to the students who handed theirs in. Students who have not submitted are not crossed off the list; their score box is simply left blank. LEFT JOIN works exactly like that.
Every row of the left table, such as customers, appears in the result at least once. If the right table, orders, has matching rows they fill in the right-hand columns; if not, those columns hold NULL, the blank box. Any report that says "include customers who have not ordered yet" is a LEFT JOIN.
Problem → Why → Solution
The problem: you wrote LEFT JOIN, but customers still vanish
Marketing asks: "show every customer, and next to them any orders from 1996-09-19 onward". You choose LEFT JOIN because every customer is required, and put the date filter in WHERE. Instead of four customers, the result holds only Antonio Moreno, on two rows.
SELECT c.customer_name, o.order_id
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id
WHERE o.order_date >= '1996-09-19'; -- removes every padded row
-- customer_name | order_id
-- Antonio Moreno | 10309
-- Antonio Moreno | 10310Why did the customers disappear?
WHERE runs after the join. On the padded rows for Alfreds and Around the Horn, o.order_date is NULL, and NULL >= '1996-09-19' is unknown rather than true, so WHERE removes them. Ana's only order is too early and goes too. The result has become an INNER JOIN. The fix is to move the date condition into ON, where it only decides which orders count as matches and never removes customer rows.
Core concept: every left row is guaranteed a place
Think of LEFT JOIN in two steps. First, exactly like INNER JOIN, find every pair that satisfies ON. Second, add back each left row that found no partner at all, with every right-hand column set to NULL. As a result, the output never has fewer rows than the left table, and in a one-to-many relationship it can have more: Antonio appears twice, once per order.
That second step is why ON and WHERE mean different things here. Conditions in ON decide which right-hand rows count as a match; if they fail, the left row still survives with NULLs. WHERE filters the finished join result afterwards, so any condition on a right-hand column throws the padded rows away, because comparing NULL gives unknown. Rule: filters on the right table go in ON; filters on the left table go in WHERE.
There is one place where testing a right-hand column in WHERE is exactly right: testing IS NULL. LEFT JOIN ... WHERE o.order_id IS NULL keeps only the padded rows and finds "customers with no orders". This pattern is called an anti-join. Test a column that can never be NULL in a real row, usually the right table's primary key, so that "no matching row" is never confused with "a matching row whose column happens to be blank".
RIGHT JOIN is LEFT JOIN mirrored: a RIGHT JOIN b returns the same rows as b LEFT JOIN a. In practice, putting the "main" table after FROM and using only LEFT JOIN keeps queries easier to read, so RIGHT JOIN is rarely seen.
- Find the pairs that satisfy ON
- Pad unmatched left rows with NULL
- Only then does WHERE filter
- Right filters: ON. Left filters: WHERE
Any right-column condition in WHERE, except IS NULL, quietly turns a LEFT JOIN back into an INNER JOIN.
General pattern
SELECT l.column_name, r.column_name
FROM left_table AS l
LEFT JOIN right_table AS r
ON r.foreign_key = l.primary_key
AND r.some_column = some_value -- right-table filter
WHERE l.other_column = other_value; -- left-table filter
-- anti-join: left rows with no match at all
SELECT l.column_name
FROM left_table AS l
LEFT JOIN right_table AS r ON r.foreign_key = l.primary_key
WHERE r.primary_key IS NULL;In the first form, the right-table filter r.some_column joins the ON clause with AND, and the left-table filter stays in WHERE. The second form is an anti-join that tests the right table's primary key for IS NULL.
Example: every customer with their orders
Of the four customers, Alfreds Futterkiste and Around the Horn have not ordered yet. LEFT JOIN keeps them in the result and fills their order columns with NULL. psql shows NULL as an empty cell, while most GUI tools print the word NULL.
SELECT c.customer_name,
o.order_id,
o.order_date
FROM customers AS c
LEFT JOIN orders AS o
ON o.customer_id = c.customer_id
ORDER BY c.customer_id, o.order_id;Code breakdown
- Lines 1-3
SELECT c.customer_name,customer_name comes from the left table, so every row has it; order_id and order_date come from the right and may be NULL.
- Line 4
FROM customers AS cPutting customers after FROM makes it the left table, which guarantees every customer a place in the result.
- Lines 5-6
LEFT JOIN orders AS oPairs customers with orders of the same customer_id and keeps the two order-less customers with NULLs. Guest order 10311 exists only on the right side, so it does not appear.
- Line 7
ORDER BY c.customer_id, o.order_id;Sorts by customer, then by order within each customer. The result has 5 rows: four customers plus one extra row for Antonio's second order.
customer_name | order_id | order_date
---------------------+----------+------------
Alfreds Futterkiste | |
Ana Trujillo | 10308 | 1996-09-18
Antonio Moreno | 10309 | 1996-09-19
Antonio Moreno | 10310 | 1996-09-20
Around the Horn | |
(5 rows)Moving the filter into ON
Now fix the query from the problem section. Moving the date condition into ON with AND brings all four customers back. Ana Trujillo's order 10308 fails the date test, so it does not count as a match and Ana appears with a NULL order rather than being removed. Result: Alfreds (NULL), Ana (NULL), Antonio (10309), Antonio (10310), Around the Horn (NULL).
SELECT c.customer_name, o.order_id
FROM customers AS c
LEFT JOIN orders AS o
ON o.customer_id = c.customer_id
AND o.order_date >= '1996-09-19'
ORDER BY c.customer_id, o.order_id;Anti-joins: customers with no orders
There are two ways to find "customers who have never bought anything", and both return Alfreds Futterkiste and Around the Horn. The first keeps only the padded rows after a LEFT JOIN. The second, NOT EXISTS, is a subquery asking "does this customer have any order?" for each row; the next lesson covers subqueries in detail. PostgreSQL usually executes both as the same anti-join plan.
SELECT c.customer_name
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL
ORDER BY c.customer_name;
SELECT c.customer_name
FROM customers AS c
WHERE NOT EXISTS (
SELECT 1 FROM orders AS o WHERE o.customer_id = c.customer_id
)
ORDER BY c.customer_name;The NOT IN and NULL trap
WHERE customer_id NOT IN (SELECT customer_id FROM orders) looks equivalent but returns zero rows on this data. Guest order 10311 has a NULL customer_id, so "1 NOT IN (2, 3, 3, NULL)" is unknown rather than true, and no customer passes. For anti-joins use NOT EXISTS or LEFT JOIN ... IS NULL.
In real projects
Where this shows up in real projects
Profile pages are full of optional data: not every user has an avatar, an address or a subscription, so the query reads users LEFT JOIN subscriptions and shows "Free plan" via COALESCE when the result is NULL. Using INNER JOIN here would make the whole profile page vanish for users without a subscription.
Anti-joins are everyday work too: users who signed up seven days ago and still have not bought anything get a reminder email; products with no category get flagged for cleanup; shipped orders that have no invoice yet go to accounting for review. For these queries to stay fast on big tables, the right table's join column needs an index.
Common mistakes
Common mistakes
1. Filtering the right table in WHERE
LEFT JOIN orders ... WHERE o.status = 'paid' removes customers with no orders and customers with no paid orders, turning the query into an INNER JOIN. For "every customer plus their paid orders" write ON ... AND o.status = 'paid'.
2. Counting with COUNT(*) after a LEFT JOIN
When counting orders per customer with LEFT JOIN and GROUP BY, COUNT(*) counts Alfreds' padded row and reports 1 instead of 0. Use COUNT(o.order_id), which skips the NULL and correctly gives 0. GROUP BY has its own lesson later.
3. Writing the anti-join with NOT IN
As soon as the subquery's result contains a single NULL, NOT IN returns no rows at all, without any error. Even if there are no NULLs today, one guest checkout tomorrow can break the report. Always prefer NOT EXISTS or LEFT JOIN ... IS NULL.
Mini challenge
Mini challenge: courses nobody has joined
courses holds four courses and enrollments holds four enrollments. The first query lists every course with its 2024 enrollments; the second finds courses that have never had a single enrollment.
- Query 1: all four courses appear; only enrollments on or after 2024-01-01 count as matches
- Query 1: the date filter goes in the right place, not in WHERE
- Query 2: write the anti-join with LEFT JOIN + IS NULL
- Query 2: show only the title
-- Query 1: every course with its 2024 enrollments
SELECT c.title, e.student, e.enrolled_on
FROM courses AS c
-- TODO: LEFT JOIN enrollments; put the 2024 date filter where it keeps every course
ORDER BY c.course_id, e.enrolled_on;
-- Query 2: courses with no enrollment at all
SELECT c.title
FROM courses AS c
-- TODO: LEFT JOIN enrollments on course_id
-- TODO: keep only the padded rows (test the right table's primary key)
;Expected: Query 1 returns four rows: SQL Basics (Moe Moe), Python 101 (NULL, its only enrollment is from 2023), Docker Intro (NULL) and Git Essentials (Ko Ko). Query 2 returns: title -------------- Docker Intro (1 row)
Show hint
In query 1 write ON e.course_id = c.course_id AND e.enrolled_on >= '2024-01-01'. In query 2 test e.enrollment_id IS NULL; it is the primary key, so it is never NULL on a real row.
Show solution
SELECT c.title, e.student, e.enrolled_on
FROM courses AS c
LEFT JOIN enrollments AS e
ON e.course_id = c.course_id
AND e.enrolled_on >= '2024-01-01'
ORDER BY c.course_id, e.enrolled_on;
SELECT c.title
FROM courses AS c
LEFT JOIN enrollments AS e ON e.course_id = c.course_id
WHERE e.enrollment_id IS NULL;Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- LEFT JOIN keeps every left row and pads the right-hand columns with NULL when nothing matches.
- Put right-table filters in ON; in WHERE they delete the padded rows and recreate an INNER JOIN.
- LEFT JOIN ... WHERE right.pk IS NULL and NOT EXISTS are safe anti-joins; avoid NOT IN when NULLs are possible.
- When counting after a LEFT JOIN, use COUNT(right.column) rather than COUNT(*).
PostgreSQL SQL Tutorial — PostgreSQL Global Development Group