Joins: Intermediate
The left table is the one written before the JOIN keyword. Choose it on purpose: it is the table whose rows you refuse to lose. In the query below, customers sits on the left, so all 4 customers come out whether or not orders holds anything for them.
SELECTc.name,o.order_id,o.totalFROM customers AS cLEFT JOIN orders AS oON c.cust_id = o.cust_id
Alice has 2 orders, so she appears twice, a row per pair, the same rows an INNER JOIN would produce. Carol appears once with her single order. Bob and Dave have no orders, so each appears once with NULL under order_id and total. The result holds 5 rows: 3 matched pairs plus 2 padded rows for the customers no order mentions.
Predicting the row count
| Customer | Matching orders | Rows in result |
|---|---|---|
| Alice | 2 | 2 |
| Bob | 0 | 1 |
| Carol | 1 | 1 |
| Dave | 0 | 1 |
| Total | 3 | 5 |
- ▸Every account, with its play count, including accounts that never played
- ▸Every product in the catalog, with last month's sales, including the ones that sold nothing
- ▸Every scheduled job, with its latest run, including jobs that have never run
A regions table has 6 rows. In stores, 3 of those regions have exactly 1 store each, 1 region has 3 stores, and 2 regions have no store at all. How many rows does the query return?
Aggregating over the padded rows
The padded rows carry NULLs, and aggregates treat those NULLs the way they always do. COUNT(o.order_id) skips them, so Bob counts 0 orders. COUNT(*) counts rows, so it would report 1 for Bob, because his padded row is still a row. SUM(o.total) over nothing but NULLs returns NULL, and COALESCE turns that into 0 for a report that should read as money.
Run it and read the 4 rows: Alice 2 orders and 80, Bob 0 and 0, Carol 1 and 75, Dave 0 and 0. Swap COUNT(o.order_id) for COUNT(*) and Bob and Dave each gain a phantom order, while their totals stay at 0 because SUM never counts rows, only values.
*. The padded row for an unmatched customer is still a row, and COUNT(*) will count it.The NULLs a LEFT JOIN writes into padded rows are a marker you can filter on. After the join, a NULL in a right-table column means either of 2 things: the row is padded, or the matching row really holds a NULL there. Pick a column that can never be NULL in the right table itself and only the first meaning remains. Then WHERE that_column IS NULL keeps exactly the left rows that found no partner. The pattern is called an anti-join: the join finds what matches, and the WHERE keeps the rest.
SELECTc.nameFROM customers AS cLEFT JOIN orders AS oON c.cust_id = o.cust_idWHERE o.order_id IS NULL
Alice's 2 rows and Carol's 1 row carry an order_id, so the test is false and they go. Bob and Dave are padded, the test is true, and they stay. The result has 2 rows, 1 per customer with no orders. An unmatched customer always appears exactly once, because a left row with no partner is emitted once, never multiplied.
Test a column that cannot be NULL
Carol has an order whose total was never recorded. The first tab reports Bob as the only customer without orders, which is true. The second tab reports Bob and Carol, and Carol's order is real: her row is a match that happens to carry a NULL, and the test cannot tell it from a padded row.
Orphans: the other direction
Swap the tables and the same pattern finds child rows that point at a parent that does not exist, which engineers call orphans. Orders whose cust_id names nobody appear after a customer deletion, a load that failed halfway, or a key typed by hand. A foreign key constraint would reject them at write time, but analytics tables rarely enforce one, so the check lives in a query.
Counting both sides in one pass
For monitoring you usually want counts rather than lists. COUNT(DISTINCT c.cust_id) counts every customer, because every customer appears at least once after the LEFT JOIN. COUNT(DISTINCT o.cust_id) ignores the NULLs on padded rows, so it counts only the customers that matched, and the difference between the 2 is the unmatched count.
- ▸Which customers signed up and never placed an order?
- ▸Which orders reference a customer we no longer have?
- ▸Which products have never appeared on an order line?
- ▸Which rows loaded into the source yesterday are missing from the warehouse today?
Which WHERE clause, added to this query, returns the products that no order line has ever referenced?
SELECTc.name,o.totalFROM customers AS cLEFT JOIN orders AS oON c.cust_id = o.cust_idWHERE o.total > 50
Alice's order totals 75, Bob's totals 30, and Carol has no order at all. By the time WHERE runs, Carol's row holds NULL under total. The comparison 75 > 50 is true, 30 > 50 is false, and NULL > 50 is NULL, and WHERE keeps only true. The result has 1 row: Alice, 75. The LEFT JOIN went to the trouble of preserving Carol and the WHERE threw her out, so the query behaves like an INNER JOIN with a longer spelling.
This query returns 40 rows. The same query with INNER JOIN in place of LEFT JOIN and nothing else changed returns how many rows?
SELECTc.name,o.totalFROM customers AS cLEFT JOIN orders AS oON c.cust_id = o.cust_idAND o.total > 50
Move the same condition into ON and it becomes part of the pairing test. Alice's order passes total > 50, so she pairs with it. Bob's order fails, so Bob has no qualifying partner and gets a padded row. Carol has no order and gets a padded row too. The result has 3 rows, every customer present, with a total only where an order cleared the bar. That answers 'show every customer, and their large orders if they have any', which the WHERE version cannot produce.
The rule, and the left-side surprise
| Condition is about | In ON | In WHERE |
|---|---|---|
| The right table | Every left row stays; a partner must also pass the condition | Left rows without a passing partner are removed |
| The left table | Every left row stays; only rows passing the condition get partners | Left rows failing the condition are removed |
Sometimes the WHERE is what you want and the padded rows are what you want back. Add them explicitly: WHERE o.total > 50 OR o.order_id IS NULL keeps Alice and Carol while still dropping Bob, whose order exists but is too small. The ON version keeps Bob padded. The 2 queries answer different questions, so decide which question is being asked before choosing.
> List every customer next to their shipped orders. A customer with no shipped order must still appear, with NULL in the order columns. Put the tiles in order; 2 of them do not belong in the query.
SELECTc.name,o.order_id,o.totalFROM customers AS cRIGHT JOIN orders AS oON c.cust_id = o.cust_id
Alice and Carol each pair with 1 order. Order O3 names customer C5, who does not exist in customers, so it comes out with NULL under name and its own order_id and total intact. The result has 3 rows, the size of orders. A LEFT JOIN from customers would never show O3 at all.
Any RIGHT JOIN can be rewritten as a LEFT JOIN by swapping the 2 table references: FROM orders o LEFT JOIN customers c with the same ON returns the same rows. Most teams write only LEFT, so that the preserved table is always the first one named and a reader never has to flip the sentence in their head. You will still meet RIGHT JOIN in queries you inherit, and the translation is always that same swap.
FULL OUTER JOIN preserves both sides
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
Alice and Carol match and appear once each with their email. Bob has an account and no session, so his session columns are NULL. User U4 has a session and no account, so the user columns are NULL. That makes 4 rows: 2 matched, 1 left-only, 1 right-only. Look at the join key on the padded rows: it is NULL on one side each time, so a query that wants a single key column must select COALESCE(u.user_id, s.user_id) rather than either side on its own.
Reconciling 2 systems
A1 and A2 land in both. A3 is billed with no CRM record, and A4 is a company the CRM knows that billing has never charged. The result has 4 rows, and the status column is the report: filter it to 'billing only' and you have the list finance asked for. A NULL c.acct_id means no CRM row matched, and a NULL b.acct_id means no billing row matched. Each key is filled in every row of its own table, so at most 1 side is NULL and the 2 WHENs could come in either order.
| Join type | Always keeps | Smallest possible result |
|---|---|---|
| INNER JOIN | Matched pairs only | 0 rows |
| LEFT JOIN | Every left row | Rows in the left table |
| RIGHT JOIN | Every right row | Rows in the right table |
| FULL OUTER JOIN | Every row of both tables | Rows in the larger table |
A WHERE condition on either side collapses a FULL OUTER JOIN the same way it collapses a LEFT JOIN: WHERE b.amount > 0 drops every CRM-only row, because their amount is NULL.
Table a has 10 rows and table b has 8 rows. Each key appears at most once in each table, and 6 keys appear in both. How many rows does a FULL OUTER JOIN b on that key return?
SELECT*FROM customers AS cINNER JOIN orders AS oON c.cust_id = o.cust_idINNER JOIN products AS pON o.prod_id = p.prod_id
Each INNER JOIN stitches the next table's columns onto the row, and Gizmo, which no order names, never lands
The customers to orders join runs first: Alice has 2 orders and Bob has 1, so the intermediate result has 3 rows. Then each of those rows is paired with its product by prod_id, giving Alice Widget, Alice Gadget and Bob Widget. Gizmo appears in no order, so it never lands, and a customer without orders would never land either, because both joins are INNER. Note that SELECT * carries 2 columns called name, one from each end of the chain, which is a reason to alias columns once a query joins more than 2 tables.
Mixing LEFT and INNER
In the first tab Bob is preserved by the LEFT JOIN, arrives at the products join with prod_id NULL, matches nothing, and is dropped: 2 rows, both Alice. In the second tab the products join is also a LEFT JOIN, so Bob comes through padded: 3 rows. Once a chain starts preserving rows, every later join that hangs off the preserved side's nullable columns must preserve them too, or the first LEFT JOIN was for nothing.
Fan-out from 2 one-to-many joins
| name | order_id | total | ticket_id |
|---|---|---|---|
| Alice | O1 | 50 | T1 |
| Alice | O1 | 50 | T2 |
| Alice | O2 | 30 | T1 |
| Alice | O2 | 30 | T2 |
- Check the row count after each join against the table you meant to preserve
- Aggregate each one-to-many child to 1 row per parent before joining 2 of them
- Keep every join after a LEFT JOIN as LEFT when its ON depends on padded columns
- Sum a column from one child table while another child is joined at row level
- Trust a total that matches for quiet customers and was never checked for busy ones
- Switch a later join to INNER to remove duplicates; it removes the preserved rows instead
customers holds 1 row, Alice. She has 3 rows in orders with totals 10, 20 and 30, and 2 rows in refunds. A query LEFT JOINs both tables onto customers by cust_id and selects SUM(o.total) grouped by name. What does it return for Alice?
> Uber's finance team closes the month by reconciling the trips table against driver payouts and rider refunds. Every trip must stay visible whether or not it has been paid out, every payout must trace back to a trip, and a trip with 3 refund lines must not have its fare counted 3 times.
Keep the rows a match would drop, find the ones nobody references, and chain joins without doubling your sums.
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)
An INNER JOIN keeps a row only when the ON condition finds it a partner in the other table. A customer with no orders makes no pairs, so the customer disappears from the result, and nothing in the output records that they existed. A LEFT JOIN changes one rule: when a row from the left table finds no partner, the engine emits that row once anyway, with NULL in every column that comes from the right table. Predicting the row count Each left row contributes either the number of partners it finds or
- Finding unmatched rows (concepts: Outer Joins)
Test a column that cannot be NULL Whether the answer is right depends on which column you test with IS NULL. The right table's primary key is the safe choice, and the right table's join key column is equally safe, since a row that matched must hold a value there. A column that can be NULL in a real row breaks the pattern, as the 2 tabs below show. Orphans: the other direction Orders O4 and O5 name customers C5 and C6, and no such customers exist, so those 2 rows come out and the other 3 do not.
- WHERE vs ON clause filtering (concepts: Execution Order)
The execution order you learned earlier explains everything in this section. FROM and JOIN run first: the ON condition decides which pairs get made and, under a LEFT JOIN, which left rows get padded instead. WHERE runs afterwards, over the finished joined rows, and keeps only the rows where its condition is true. A condition in ON shapes the pairing. A condition in WHERE removes rows from the result of the pairing. Under an INNER JOIN the placement makes no difference to the rows you get. A pair
- RIGHT JOIN & FULL OUTER (concepts: Full Outer Joins)
A RIGHT JOIN preserves the table written after the JOIN keyword. Every right row comes out at least once, and a right row with no partner on the left is padded with NULL in every left-table column. It is the mirror of the first section, and the row count follows the mirror rule: never fewer rows than the right table. FULL OUTER JOIN preserves both sides A FULL OUTER JOIN keeps every row from both tables. Matched rows appear as pairs. An unmatched left row is padded on the right, an unmatched rig
- Multiple JOINs (concepts: Multiple JOINs)
A chain of joins is defined left to right: the result is the same as if the first join produced an intermediate result, that result became the left input of the second join, and so on down the chain. The engine may physically run inner joins in another order to save work, but it cannot change which rows an outer join preserves. Every ON condition can reference any column that has already arrived, so the third table can be joined on a column from the second, from the first, or from both. Mixing L