Joins: Intermediate
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.
| cust_id | name |
|---|---|
| C1 | Alice |
| C2 | Bob |
| C3 | Carol |
| C4 | Dave |
| order_id | cust_id | total |
|---|---|---|
| O1 | C1 | 50 |
| O2 | C1 | 30 |
| O3 | C3 | 75 |
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.
SELECTc.name,o.order_id,o.totalFROM customers AS cLEFT JOIN orders AS oON c.cust_id = o.cust_id
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.
| Customer | Orders that match | Rows in result | Right-side columns |
|---|---|---|---|
| Alice | 2 | 2 | filled from O1 and O2 |
| Bob | 0 | 1 | all NULL |
| Carol | 1 | 1 | filled from O3 |
| Dave | 0 | 1 | all 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.
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.
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.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?
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.
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.
SELECTc.nameFROM customers AS cLEFT JOIN orders AS oON c.cust_id = o.cust_idWHERE o.order_id IS NULL
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.
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 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.
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.
- Finds parents with no children
- Example: customers with no orders
- Usually a real business fact
- Finds children with no parent
- Example: refunds naming an absent order
- A data fault to investigate
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.
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.
- ▸
ONtests each pair of rows and accepts or rejects it. - ▸Padding adds each left row with no accepted pair, with
NULLon the right. - ▸
WHEREtests 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.
SELECTc.name,o.totalFROM customers AS cLEFT JOIN orders AS oON c.cust_id = o.cust_idWHERE o.total > 60
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.
SELECTc.name,o.totalFROM customers AS cLEFT JOIN orders AS oON c.cust_id = o.cust_idAND o.total > 60
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 about | Written in ON | Written 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. |
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?
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.
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.
- 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
- 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
> 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.
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.
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.
SELECTc.name,o.order_id,o.totalFROM orders AS oRIGHT JOIN customers AS cON o.cust_id = c.cust_id
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.
SELECTu.user_id AS account_id,u.name,s.user_id AS session_user,s.emailFROM users AS uFULL OUTER JOIN user_sessions AS sON u.user_id = s.user_id
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 type | Pairs | Left-only rows | Right-only rows | Total |
|---|---|---|---|---|
| INNER JOIN | 2 | 0 | 0 | 2 |
| LEFT JOIN | 2 | 1 (U2) | 0 | 3 |
| RIGHT JOIN | 2 | 0 | 1 (U4) | 3 |
| FULL OUTER JOIN | 2 | 1 (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.
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.
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.
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.
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.
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.
| After | Rows | Who is missing |
|---|---|---|
| FROM customers | 4 | Nobody |
| INNER JOIN orders | 3 | Bob and Dave, who have no orders |
| INNER JOIN products | 3 | Still 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.
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.
- ▸Each
ONclause links the new table to a table already in the query. - ▸After a
LEFT JOIN, joins that depend on the optional table areLEFTas well. - ▸The row count after each join matches the count you predicted.
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?
> 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.ON, adding WHERE b.booking_id IS NULL turns the report into the coaching list: listings with no bookings this month.bookings goes in ON. In WHERE it would remove every listing with no booking this month, the exact rows the team asked for.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.LEFT JOIN returns every accepted pair plus each unmatched left row once, padded with NULL. Its row count is pairs plus unmatched left rows.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.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
- LEFT JOIN (concepts: Outer Joins)
Every left row survives Kept at least once Counting through a LEFT JOIN
- 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
- WHERE vs ON clause filtering (concepts: Execution Order)
Move the test into ON A left-table condition in ON The OR IS NULL patch
- RIGHT JOIN & FULL OUTER (concepts: Full Outer Joins)
FULL OUTER JOIN protects both tables Reading a reconciliation
- 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.