IntermediateSQL · 33 min · 17 challenges

Joins: Intermediate

A host-success analyst at Airbnb is asked for every Lisbon listing alongside its bookings this month, so the team can coach hosts with empty calendars. The first query returns only listings that got booked. The empty ones, the whole point of the report, never show up. Which join you write decides whether they appear.

LEFT JOIN

Daily Life
Interviews

An INNER JOIN returns a row only where the ON condition accepts a pair. A row with no partner leaves no trace in the result. That is the right behavior for some questions and a silent bug for others. Take a store with 4 customers and 3 orders.

customers
cust_idname
C1Alice
C2Bob
C3Carol
C4Dave
orders
order_idcust_idtotal
O1C150
O2C130
O3C375

Ask for every customer with their orders using INNER JOIN and you get 3 rows: Alice twice and Carol once. Bob and Dave have placed no orders, so no pair exists for them and they are gone. A report titled "all customers" now lists 2 of the 4, and nothing in the output says so.

Every left row survives

LEFT JOIN changes one thing. It returns every pair the ON condition accepts, exactly as INNER JOIN does. Then it adds each left row that found no partner, once, with NULL in every column from the right table. The left table is the one named in FROM. The right table is the one named after LEFT JOIN.

SELECT
c.name,
o.order_id,
o.total
FROM customers AS c
LEFT JOIN orders AS o
ON c.cust_id = o.cust_id
customers4 rows
cust_id
name
C1
Alice
C2
Bob
C3
Carol
C4
Dave
orders3 rows
order_id
cust_id
total
O1
C1
50
O2
C1
30
O3
C3
75
Preparing the animation

Join customers to orders with LEFT JOIN on cust_id and the result has 5 rows, each with a reason. Alice pairs with orders O1 and O2, so she appears twice. Carol pairs with O3. Bob and Dave pair with nothing, so each appears once with NULL for order_id and total. Those NULLs mean "no such order exists", which is different from an order whose total is 0.

CustomerOrders that matchRows in resultRight-side columns
Alice22filled from O1 and O2
Bob01all NULL
Carol11filled from O3
Dave01all NULL

You can predict the size of any LEFT JOIN result before running it. The row count equals the number of accepted pairs plus the number of left rows with no pair. Here that is 3 + 2 = 5. An INNER JOIN on the same tables stops at the 3.

Kept at least once

LEFT JOIN guarantees each left row appears at least once. It makes no promise of exactly once. Alice has 2 orders, so she fills 2 rows: a one-to-many relationship multiplies left rows here the same way it does under INNER JOIN. When the report needs one row per customer, group after the join.

Counting through a LEFT JOIN

Grouping a LEFT JOIN result has one trap. Bob's group contains one row, the NULL-padded one, so COUNT(*) reports 1 for a customer with no orders. COUNT(o.order_id) skips NULLs and reports 0, which is the true order count. SUM(o.total) over only NULLs returns NULL, so wrap it in COALESCE when the report should say 0.

SELECT
c.name,
COUNT(*) AS row_count,
COUNT(o.order_id) AS order_count,
COALESCE(SUM(o.total), 0) AS total_spent
FROM customers AS c
LEFT JOIN orders AS o
ON c.cust_id = o.cust_id
GROUP BY c.name
ORDER BY c.name
Result
namerow_countorder_counttotal_spent
Alice2280
Bob100
Carol1175
Dave100
4 rows

Run it and read Bob's row. row_count is 1, while order_count and total_spent are both 0. On Alice's row the 2 counts agree at 2, and the total is 80. row_count and order_count disagree only for the customers the join had to pad.

TIP
Read A LEFT JOIN B as a promise about A: every row of A comes out of the join. B only decorates those rows. Before writing the join, decide which table's rows the report must never lose, and put that table in FROM.
Multiple Choice

A plans table has 3 rows. In subscribers, 4 rows point at Basic and 1 row points at Pro, and the third plan, Plus, has no subscribers. How many rows does this query return?

SELECT
p.plan_name,
s.subscriber_id
FROM plans AS p
LEFT JOIN subscribers AS s
ON p.plan_id = s.plan_id

The habit to build is accounting for rows. Before you run a LEFT JOIN, write down how many left rows have partners, how many pairs they form and how many left rows stand alone. If the result's row count differs from your number, something is wrong with the data or with your picture of it, and you want to know which.

Finding unmatched rows

Daily Life
Interviews

The NULLs a LEFT JOIN adds carry information. A padded row exists only because its left row found no partner. So a query that keeps only the padded rows answers a question no INNER JOIN can: which rows have nothing on the other side? Customers who never ordered fit that shape. So do products nobody bought, and refunds that point at an absent order.

The recipe has 2 parts. LEFT JOIN from the table whose rows you are checking. Then, in WHERE, keep the rows where the right table's key IS NULL. This shape is called an anti-join, because it returns the left rows the join could not match.

SELECT
c.name
FROM customers AS c
LEFT JOIN orders AS o
ON c.cust_id = o.cust_id
WHERE o.order_id IS NULL
customers4 rows
cust_id
name
C1
Alice
C2
Bob
C3
Carol
C4
Dave
orders3 rows
order_id
cust_id
O1
C1
O2
C1
O3
C3
Preparing the animation

Apply the recipe to customers and orders, and follow the order the database works in. The join runs first and builds 5 rows. Alice has 2 and Carol has 1, and Bob and Dave each get a padded row. WHERE runs next and tests o.order_id IS NULL on each of the 5. Alice's and Carol's rows hold real order ids, so the test is false. Bob's and Dave's hold NULL, so the test is true. The result is 2 names: Bob and Dave.

Test a column that is never NULL

Which column you test matters. o.order_id is the primary key of orders, so no real order has a NULL there. A NULL in that column can only come from padding. Now suppose orders also had a nullable coupon column and you tested o.coupon IS NULL instead. Every customer who ordered without a coupon would pass the test and be reported as having no orders. Test the right table's primary key, or the join column itself.

TIP
WHERE o.order_id = NULL returns zero rows. Under three-valued logic a comparison with NULL is never true, so only IS NULL can find the padded rows.

Missing rows and orphaned rows

The same query shape finds 2 different problems, and the difference is which table sits on the left. Put the parent table on the left and you find parents with no children: customers with no orders. Those rows are often a legitimate business fact. Put the child table on the left and you find children with no parent. A child row whose foreign key matches no primary key is called an orphan. An orphan signals a fault: usually its parent was deleted or never loaded, though sometimes the parent was written with a different key.

The store also keeps a refunds table, where each refund names the order it reverses. Every order_id in it should exist in orders. This query checks.

SELECT
r.refund_id,
r.order_id,
r.amount
FROM refunds AS r
LEFT JOIN orders AS o
ON r.order_id = o.order_id
WHERE o.order_id IS NULL
Result
refund_idorder_idamount
R2O945
1 row

Refunds R1 and R3 are fine, since R1 reverses O2 and R3 reverses O1. R2 names order O9, and orders has no O9. The join pads R2 with NULL, the WHERE keeps it, and the result is one row: R2, O9, 45. The SELECT list reads r.order_id, the refund's own copy of the key, because o.order_id is NULL on every row this query returns.

✓Missing (parent on the left)
  • Finds parents with no children
  • Example: customers with no orders
  • Usually a real business fact
✗Orphaned (child on the left)
  • Finds children with no parent
  • Example: refunds naming an absent order
  • A data fault to investigate
Multiple Choice

A products table has one row per product. order_items has one row per product sold, with a product_id foreign key. Which query lists the products that have never been sold?

Why orphans happen at all

A foreign key constraint would reject R2 at insert time. Analytical tables are often loaded by separate jobs on separate schedules, with nothing enforcing the relationship between them. A refund can land an hour before its order does. A delete can remove an order and leave its refunds behind. An anti-join run on a schedule catches this before a dashboard does. An INNER JOIN from refunds to orders would drop R2 without a word, and total refunds would come up 45 short.

Loading the challenge
Before running an anti-join, write it as one sentence: "rows of the left table that have nothing on the right". If that sentence names the rows you want, the tables are in the right order. If it names the opposite set, swap them.

WHERE vs ON clause filtering

Daily Life
Interviews

A join query has 2 places to put a condition. ON is consulted while rows are being paired: it decides which pairs are accepted. WHERE is consulted after the join has finished: it decides which finished rows stay. Under INNER JOIN the 2 places give the same result, because a pair rejected early and a row removed late are both gone. Under LEFT JOIN they differ, and the reason is the padding step that sits between them.

The order a LEFT JOIN works in
  • ▸ON tests each pair of rows and accepts or rejects it.
  • ▸Padding adds each left row with no accepted pair, with NULL on the right.
  • ▸WHERE tests every row that exists after padding.

Take one request: list every customer, and show their orders over 60 if they have any. The first attempt puts the amount test in WHERE.

SELECT
c.name,
o.total
FROM customers AS c
LEFT JOIN orders AS o
ON c.cust_id = o.cust_id
WHERE o.total > 60
customers4 rows
cust_id
name
C1
Alice
C2
Bob
C3
Carol
C4
Dave
orders3 rows
order_id
cust_id
total
O1
C1
50
O2
C1
30
O3
C3
75
Preparing the animation

The join builds the familiar 5 rows, then WHERE o.total > 60 tests each one. Alice's rows hold 50 and 30, so both are false. Carol's holds 75, so it is true. The rows for Bob and Dave hold NULL, and NULL > 60 evaluates to NULL, which WHERE treats the same as false. One row is left: Carol, 75. The request said every customer, and 3 of the 4 are gone. A WHERE test on a right-table column has turned the LEFT JOIN back into an INNER JOIN.

Move the test into ON

The fix moves the amount test up into the ON clause, joined to the key match with AND.

SELECT
c.name,
o.total
FROM customers AS c
LEFT JOIN orders AS o
ON c.cust_id = o.cust_id
AND o.total > 60
customers4 rows
cust_id
name
C1
Alice
C2
Bob
C3
Carol
C4
Dave
orders3 rows
order_id
cust_id
total
O1
C1
50
O2
C1
30
O3
C3
75
Preparing the animation

Now a pair is accepted only if the ids match and the total is over 60. Alice's 2 orders match her id and fail the amount test, so Alice has no accepted pair. Padding treats her the same as Bob and Dave: one row, NULL on the right. Carol's order passes both tests. The result keeps one row for each of the 4 customers, and only Carol's shows a total. The condition narrowed which orders may attach, and it could not remove a customer.

Condition is aboutWritten in ONWritten in WHERE
The right table (orders)Limits which orders attach. Every customer stays.Removes padded rows. Acts like INNER JOIN.
The left table (customers)Limits which customers get orders attached. Every customer stays.Removes those customers. Safe and expected.
Multiple Choice

In the store's tables, Alice has orders of 50 and 30 and Carol has one of 75, while Bob and Dave have none. What does this query return?

SELECT
c.name,
o.total
FROM customers AS c
LEFT JOIN orders AS o
ON c.cust_id = o.cust_id
AND o.total > 40

A left-table condition in ON

A condition on the left table behaves in a way that surprises people when it is written in ON. Suppose you want to leave Alice out and write AND c.name != 'Alice' in the ON clause. Alice still appears. ON can only reject pairs, so her 2 orders fail to attach and padding returns her with NULLs. To remove left rows, the condition belongs in WHERE.

SELECT
c.name,
o.order_id
FROM customers AS c
LEFT JOIN orders AS o
ON c.cust_id = o.cust_id
AND c.name != 'Alice'
ORDER BY c.name
Result
nameorder_id
AliceNULL
BobNULL
CarolO3
DaveNULL
4 rows

The OR IS NULL patch

A common repair keeps the test in WHERE and adds an escape hatch: WHERE o.total > 60 OR o.total IS NULL. It rescues Bob and Dave, whose padded rows now pass. It still loses Alice. Her rows are real orders with totals of 50 and 30, so they fail both halves of the test. The patch returns 3 customers where the ON version returns 4. It answers "customers with a big order or no orders", which is a different question.

✓Do
  • Put right-table filters in ON when every left row must stay
  • Put left-table filters in WHERE to remove left rows
  • Keep IS NULL anti-join tests in WHERE, where padded rows exist
✗Don't
  • Filter a right-table column in WHERE and expect unmatched rows to survive
  • Patch a WHERE filter with OR IS NULL and call it equivalent
Complete the SQL

> Marketing wants every customer listed once per order of 50 or more. A customer with no such order must still appear, with NULL for the total. Arrange the pieces into that query. 2 tiles do not belong.

1
2
3
4
5

For each condition, ask: when no right row passes it for some left row, should that left row disappear or stay with NULLs beside it? Disappear means WHERE. Stay means ON. Ask it for each condition separately, because one query often needs both answers.

RIGHT JOIN & FULL OUTER

Daily Life
Interviews

LEFT JOIN protects the table in FROM. RIGHT JOIN protects the other one: every row of the table named after RIGHT JOIN comes out of the join, and the FROM table's columns are padded with NULL where no pair was accepted. To see how little that changes, write the customer report with the tables in the opposite order.

SELECT
c.name,
o.order_id,
o.total
FROM orders AS o
RIGHT JOIN customers AS c
ON o.cust_id = c.cust_id
orders3 rows
order_id
cust_id
total
O1
C1
50
O2
C1
30
O3
C3
75
customers4 rows
cust_id
name
C1
Alice
C2
Bob
C3
Carol
C4
Dave
Preparing the animation

orders is now in FROM and customers is on the protected right side. The result holds the same 5 rows as the LEFT JOIN that opened this lesson. Alice pairs with O1 and O2 and Carol with O3, while Bob and Dave get NULL order columns. A RIGHT JOIN B and B LEFT JOIN A always return the same rows. Because any RIGHT JOIN can be rewritten this way, many teams write LEFT JOIN only. A query that reads "start with the rows I must keep, then attach extras" is faster to check than one where the protected table appears last.

FULL OUTER JOIN protects both tables

Sometimes neither table is the trusted one. Say a users table lists accounts, and a user_sessions table holds one row per user seen in the login system, with the email they signed in with, so each user_id appears in it at most once. You want to know where the 2 disagree. FULL OUTER JOIN returns every accepted pair, then every unmatched left row padded on the right, then every unmatched right row padded on the left.

SELECT
u.user_id AS account_id,
u.name,
s.user_id AS session_user,
s.email
FROM users AS u
FULL OUTER JOIN user_sessions AS s
ON u.user_id = s.user_id
users3 rows
user_id
name
U1
Alice
U2
Bob
U3
Carol
user_sessions3 rows
user_id
email
U1
alice@co
U3
carol@co
U4
dan@co
Preparing the animation

There are 3 accounts and 3 session rows, and the full join returns 4 rows. U1 and U3 appear in both tables, so each forms one pair. Bob's account, U2, has no session, so his row has NULL in both session columns. The session for U4 has no account: its row has NULL in both account columns. Each NULL tells you which side is missing.

Join typePairsLeft-only rowsRight-only rowsTotal
INNER JOIN2002
LEFT JOIN21 (U2)03
RIGHT JOIN201 (U4)3
FULL OUTER JOIN21 (U2)1 (U4)4

All 4 join types build the same pairs. They differ only in which unmatched rows they add back. That gives a check for any full join: its row count equals the LEFT JOIN count plus the RIGHT JOIN count minus the INNER JOIN count. Here 3 + 3 - 2 = 4.

Multiple Choice

warehouse_stock has 5 rows and store_stock has 4 rows. Each has a unique sku, and 3 skus appear in both tables. How many rows does a FULL OUTER JOIN on sku return?

Reading a reconciliation

Raw full-join output is awkward to scan, because the key lives in 2 columns and either may be NULL. 2 additions fix that. COALESCE(u.user_id, s.user_id) returns whichever key is present, giving one filled key column. A CASE expression on the 2 keys labels each row with where it was found.

SELECT
COALESCE(u.user_id, s.user_id) AS user_key,
CASE
WHEN s.user_id IS NULL THEN 'account only'
WHEN u.user_id IS NULL THEN 'session only'
ELSE 'both'
END AS found_in
FROM users AS u
FULL OUTER JOIN user_sessions AS s
ON u.user_id = s.user_id
ORDER BY user_key
Result
user_keyfound_in
U1both
U2account only
U3both
U4session only
4 rows

The 4 rows now read U1 both, U2 account only, U3 both, U4 session only. Add WHERE u.user_id IS NULL OR s.user_id IS NULL and only the 2 disagreements remain: an anti-join in both directions at once. The same query reconciles any 2 sources that should agree, such as a billing system's invoices against a ledger's entries.

Loading the challenge

Choose the join by naming the rows you refuse to lose. To keep the rows of one table, use LEFT JOIN with that table in FROM; to keep the rows of both tables, FULL OUTER JOIN; to keep neither, INNER JOIN. RIGHT JOIN adds no new answer to that list, so recognizing it when you read it is enough.

Multiple JOINs

Daily Life
Interviews

Real questions rarely stop at 2 tables. "Which products did each customer buy?" needs orders to connect customers to products. A query with 3 tables contains 2 joins, read in the order written. The first join produces a result table. The next join treats that result as its left side and attaches one more table to it. Each join is the same pairing step you already know, run again on a wider table.

Each order in the store's orders table also records the product sold, in a prod_id column the earlier examples left out.

customers
cust_idPKVARCHAR
nameVARCHAR
orders
order_idPKVARCHAR
cust_idFKVARCHAR
prod_idFKVARCHAR
totalINTEGER
products
prod_idPKVARCHAR
productVARCHAR
SELECT
c.name,
o.order_id,
p.product
FROM customers AS c
INNER JOIN orders AS o
ON c.cust_id = o.cust_id
INNER JOIN products AS p
ON o.prod_id = p.prod_id
ORDER BY o.order_id
Result
nameorder_idproduct
AliceO1Widget
AliceO2Gadget
CarolO3Widget
3 rows

Trace the 3-table query one join at a time. customers joined to orders gives 3 rows: Alice with O1, Alice with O2, Carol with O3. Bob and Dave drop here. That 3-row result then joins to products on o.prod_id, a column that arrived with the first join. O1 and O3 both find Widget and O2 finds Gadget, so the count stays at 3. Gizmo, which no order names, never enters the result.

AfterRowsWho is missing
FROM customers4Nobody
INNER JOIN orders3Bob and Dave, who have no orders
INNER JOIN products3Still Bob and Dave. Gizmo never joined.

One INNER JOIN can undo a LEFT JOIN

Now the request changes: keep every customer, and show product names where orders exist. You switch the first join to LEFT JOIN and leave the product join as INNER JOIN. Bob and Dave survive the first join with NULL in o.prod_id. Then the product join asks whether NULL = p.prod_id for some product. A comparison with NULL is never true, so their rows find no pair, and an INNER JOIN drops rows with no pair. The customers you protected in step 1 are removed in step 2.

The INNER JOIN to products discards the padded rows for Bob and Dave. 3 rows come back.
SELECT
c.name,
o.order_id,
p.product
FROM customers AS c
LEFT JOIN orders AS o
ON c.cust_id = o.cust_id
INNER JOIN products AS p
ON o.prod_id = p.prod_id
ORDER BY c.name, o.order_id
Result
nameorder_idproduct
AliceO1Widget
AliceO2Gadget
CarolO3Widget
3 rows

So once a join is LEFT, every later join that hangs off the optional table must be LEFT too. Here products attaches through orders, and orders is optional, so the product join has to tolerate rows where orders is absent.

Count rows after every join

Long join chains fail quietly. A join that drops rows or multiplies them still returns a result that looks reasonable. The defense is to build the chain one join at a time. Start with the FROM table alone and note its row count. Add one join and predict the new count before running it. A drop means rows found no partner. A rise means the new table holds several rows per key. Either may be correct, and you should be able to say which before adding the next table.

Before trusting a join chain
  • ▸Each ON clause links the new table to a table already in the query.
  • ▸After a LEFT JOIN, joins that depend on the optional table are LEFT as well.
  • ▸The row count after each join matches the count you predicted.
Multiple Choice

A tickets table holds one row per support ticket, with a cust_id. Alice has 3 tickets and no other customer has any. With the store's 4 customers and 3 orders (2 for Alice, 1 for Carol), how many rows does this query return?

SELECT
c.name,
o.order_id,
t.ticket_id
FROM customers AS c
LEFT JOIN orders AS o
ON c.cust_id = o.cust_id
LEFT JOIN tickets AS t
ON c.cust_id = t.cust_id
Every technique in this lesson is the pairing model with one addition: a rule for rows that found no partner. The rule says which side's unmatched rows survive, if any, and you decide whether each condition acts before or after that rule runs. A chain of joins repeats the decision once per table.
PUTTING IT ALL TOGETHER

> Return to the Lisbon listings report. The analyst has 3 tables: listings, whose rows must all appear, bookings, which holds stays, and hosts, which holds the contact name. Finance also keeps a payouts table that should agree with bookings.

listings LEFT JOIN bookings keeps the empty listings the first draft lost, each with NULL booking columns.
With the this-month condition in ON, adding WHERE b.booking_id IS NULL turns the report into the coaching list: listings with no bookings this month.
The this-month condition on bookings goes in ON. In WHERE it would remove every listing with no booking this month, the exact rows the team asked for.
The join to hosts hangs off listings, which is never optional, so it can be INNER only if every listing's host exists in hosts. If one may be missing, LEFT JOIN keeps that listing in the report. A join that hangs off bookings has to be LEFT.
bookings FULL OUTER JOIN payouts shows bookings never paid out and payouts with no booking in one result, and the row count check is LEFT plus RIGHT minus INNER.
KEY TAKEAWAYS
LEFT JOIN returns every accepted pair plus each unmatched left row once, padded with NULL. Its row count is pairs plus unmatched left rows.
An anti-join is a LEFT JOIN followed by WHERE on the right table's key IS NULL. Parent on the left finds missing children, and child on the left finds orphans.
ON decides which pairs attach, and WHERE decides which finished rows stay. A right-table test in WHERE turns a LEFT JOIN back into an INNER JOIN.
A RIGHT JOIN B returns the same rows as B LEFT JOIN A. FULL OUTER JOIN keeps unmatched rows from both sides: the LEFT count plus the RIGHT count minus the INNER count.
In a chain, each join's result is the next join's left side. After a LEFT JOIN, later joins through the optional table stay LEFT, and the row count is checked after every join.

Keep unmatched rows, find what is missing, and control exactly when a filter runs in a join.

Keeping rows even without a match

Category
SQL
Difficulty
intermediate
Duration
33 minutes
Challenges
17 hands-on challenges

Topics covered: LEFT JOIN, Finding unmatched rows, WHERE vs ON clause filtering, RIGHT JOIN & FULL OUTER, Multiple JOINs

Lesson Sections

  1. LEFT JOIN (concepts: Outer Joins)

    Every left row survives Kept at least once Counting through a LEFT JOIN

  2. Finding unmatched rows (concepts: Outer Joins)

    Test a column that is never NULL Missing rows and orphaned rows The same query shape finds 2 different problems, and the difference is which table sits on the left. Put the parent table on the left and you find parents with no children: customers with no orders. Those rows are often a legitimate business fact. Put the child table on the left and you find children with no parent. A child row whose foreign key matches no primary key is called an orphan. An orphan signals a fault: usually its paren

  3. WHERE vs ON clause filtering (concepts: Execution Order)

    Move the test into ON A left-table condition in ON The OR IS NULL patch

  4. RIGHT JOIN & FULL OUTER (concepts: Full Outer Joins)

    FULL OUTER JOIN protects both tables Reading a reconciliation

  5. Multiple JOINs (concepts: Multiple JOINs)

    One INNER JOIN can undo a LEFT JOIN Count rows after every join Every technique in this lesson is the pairing model with one addition: a rule for rows that found no partner. The rule says which side's unmatched rows survive, if any, and you decide whether each condition acts before or after that rule runs. A chain of joins repeats the decision once per table.