Joins that change the row count
Part of the free LogicWiz Data Engineering course, Module 2: SQL for pipelines. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 9:05 on Monday. Tess opens the June revenue number you sent her on Friday: $27,176.56. Then she adds up the payments table herself and gets $8,514.73 of captured money. No job failed and nobody added money: your join did.
You'll learn to
- Predict when a join keeps, drops or multiplies rows
- Fix a fan-out by summing each table before you join
- Find rows with no match, without the NOT IN trap
- Read a join in a plan: nested loop, hash or merge
Learn
One payment, counted twice
Here is the query behind the number. You joined orders to order_items (the lines of each order) and to payments, then summed amount.
Take order 1002. It has two lines, a Hand Cream and Wireless Earbuds, and it was paid once: $68.74. A join pairs each row on the left with every matching row on the right. So order 1002 comes out as two rows, one per line, and the payment sits on both.
One row became two. That is called a fan-out. Sum amount now and the $68.74 counts twice.
Orders 1002 and 1003 after both joins
| orderid | line | product | paymentid | amount |
|---|---|---|---|---|
| 1002 | 1 | Hand Cream | 5002 | 68.74 |
| 1002 | 2 | Wireless Earbuds | 5002 | 68.74 again |
| 1003 | 1 | Travel Guide | 5003 | 166.50 |
| 1003 | 2 | Backpack | 5003 | 166.50 again |
Each order was paid once but has two lines, so its payment appears twice. SUM(amount) over these four rows gives 470.48, not 235.24. Across the whole shop the same copying turns $8,514.73 into $27,176.56.
Watch rows multiply
Two small tables, orders and payments; choosing a join key that repeats on one side makes the joined rows multiply, and a checkbox applies the fix.
Pick the join key and the join type, and watch the row count and the sum. Then tick the fix and watch both come back.
Ask what one row means
Nora reads your query and asks one thing: "What does one row mean in each table?"
That meaning has a name: the grain. In orders, one row is one order. In order_items, one row is one line of an order. In payments, one row is one payment attempt.
A fan-out is not a bug by itself. One row per line is exactly right for a lines report. It becomes a bug when you sum a column that belongs to the order, such as a payment amount, after the order has been copied.
So before any join, ask two things. What is the grain of each side? Can the key repeat on the right?
Count before and after every join
SELECT
(SELECT COUNT(*) FROM orders) AS orders,
(SELECT COUNT(*)
FROM orders o
JOIN order_items i ON i.order_id = o.order_id) AS after_lines,
(SELECT COUNT(*)
FROM orders o
JOIN order_items i ON i.order_id = o.order_id
JOIN payments p ON p.order_id = o.order_id) AS after_lines_and_payments;
80 orders become 201 rows once the lines are joined, one per line. They become 216 once payments are joined too: every line is paired with every payment of its order.
The same habit, on the raw files
import duckdb
def count(sql):
return duckdb.sql(sql).fetchone()[0]
print("orders:", count("SELECT COUNT(*) FROM 'data/orders.csv'"))
print("after inner join:", count("""
SELECT COUNT(*)
FROM 'data/orders.csv' o
JOIN 'data/order_items.csv' i ON i.order_id = o.order_id
"""))
print("after left join:", count("""
SELECT COUNT(*)
FROM 'data/orders.csv' o
LEFT JOIN 'data/order_items.csv' i ON i.order_id = o.order_id
"""))
The same SQL runs on the CSV exports in DuckDB: 80, then 201, then 202. The left join keeps order 1058, which has no lines. Counting before and after is a habit, not a Postgres feature.
Remember: count the rows before a join and after it. If the count grew, a key repeats on the other side, and any sum you take next is too high.
Sum first, then join
The fix is to stop joining two "many" tables to the same order.
First bring each child table down to one row per order: add up the lines of each order, and add up its captured payments. Write each one as a CTE, a named subquery that starts with WITH. Then join those results to orders. Every join is now one row to one row, so nothing is copied.
Use LEFT JOIN, so an order with no lines or no payment stays in the result, and COALESCE(x, 0) when you want a zero where there is nothing. The row count after the joins must still be 80. Check it.
Order 1002: join first, or sum first
Order 1002 has two lines and one payment of 68.74 dollars. Joined directly, the payment appears on two rows; summed to one row per order first, it appears once.
The data. Order 1002 has two lines and one payment of $68.74. Nothing is joined yet.
Join first. Each line pairs with the payment, so the result has two rows and both carry $68.74.
SUM(amount)says $137.48.Sum first. Add up the lines: one row, $68.74. Add up the payments: one row, $68.74. Now the join is one row to one row, and the payment counts once.
Press Next step and watch the Result box: two rows when you join first, one row when you sum first.
Sum each table, then join one to one
WITH lines AS (
SELECT order_id, SUM(qty * unit_price) AS line_total
FROM order_items
GROUP BY order_id
),
paid AS (
SELECT order_id, SUM(amount) AS paid
FROM payments
WHERE status = 'captured'
GROUP BY order_id
)
SELECT o.order_id, o.status, l.line_total, p.paid
FROM orders o
LEFT JOIN lines l ON l.order_id = o.order_id
LEFT JOIN paid p ON p.order_id = o.order_id
ORDER BY o.order_id;
Exactly 80 rows. Scroll to order 1033, which was paid twice, and to order 1058, which has no lines at all. The problems are now in plain sight, not hidden inside a sum.
Some rows vanish: the key is empty
A join can also lose rows, and it does that quietly too.
In events, 41 of the 192 rows come from visitors who were not logged in. Their user_id is NULL, which means "no value". A NULL key matches nothing, not even another NULL, because NULL = NULL is not true: it is unknown.
So an inner join from events to customers drops all 41 rows, with no error. That is fine for a per-customer report. It is wrong for "total page views".
When a join key can be NULL, decide on purpose: an inner join drops those rows, a LEFT JOIN keeps them.
Finding what is missing
Tess now wants the opposite list: orders with no captured payment. Pipelines ask this all the time. Customers who never ordered. Lines whose product does not exist.
A query for "rows with no match" is called an anti-join. There are two safe ways to write it:
LEFT JOINthe other table, then keep the rows where its keyIS NULLWHERE NOT EXISTS (SELECT 1 FROM ... WHERE ...)
A third way, NOT IN, has a trap that comes up further down. And one detail matters. If only some rows count as a match (only captured payments), put that condition in the ON clause or inside the NOT EXISTS. In WHERE it runs after the join and throws away the very NULL rows you are looking for.
Two anti-joins
-- customers who never placed an order
SELECT c.customer_id, c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL;
-- orders with no captured payment
SELECT o.order_id, o.status
FROM orders o
WHERE NOT EXISTS (
SELECT 1
FROM payments p
WHERE p.order_id = o.order_id
AND p.status = 'captured'
)
ORDER BY o.order_id;
Customer 12 is Maya Chen's second sign-up, and customer 30 never bought. Of the 11 orders with no captured payment, 9 are cancelled, which is expected. Orders 1047 and 1058 deserve a question to Dana, who owns the shop's app.
Under the hood: build, then probe
Now open the engine. How does Postgres find the matching rows?
Think of a clerk matching 201 delivery slips to 80 order folders. Searching the whole pile of folders for every slip is slow. So the clerk first files the folders in a cabinet, one drawer per order number. Then each slip goes straight to its drawer.
Postgres does the same. It reads the smaller table once into a table in memory that it can look up by key: a hash table. That is the build side. Then it streams the other table past it, one lookup per row. That is the probe side. The whole method is called a hash join.
A hash join, step by step
Orders, the smaller table, are read into a hash table of 1,024 buckets; the 201 order lines then stream past it, and each line that finds its order comes out as a joined row.
Build. Postgres reads the smaller table,
orders, once. It files each of the 80 orders in the hash table under itsorder_id. The table has 1,024 buckets (the drawers) and takes 7 kB.Probe. Now the 201 lines stream past, one at a time. For each line, Postgres looks up its
order_idin the hash table: one lookup, no searching.Output. Every line finds its order, so 201 joined rows come out. 80 rows went in on one side and 201 came out: that jump is the fan-out, visible before it ever reaches a sum.
Follow the colour: blue is read first and kept, violet flows past it, teal is what comes out. The numbers are the ones Postgres prints for the first query below.
See the join, and the fan-out, in the plan
-- ANALYZE runs the query and adds the real row counts;
-- the OFF options drop numbers that change from run to run
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT COUNT(*)
FROM orders o
JOIN order_items i ON i.order_id = o.order_id;
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT COUNT(*)
FROM orders o
JOIN order_items i ON i.order_id = o.order_id
JOIN payments p ON p.order_id = o.order_id;
EXPLAIN prints the plan: the steps Postgres chose. Read it from the innermost line out. In the second plan Postgres first joins payments to orders (85 rows), hashes that, and probes it with the 201 lines: Hash Join (actual rows=216.00). The join order is chosen by the planner, the part of Postgres that decides how to run a query. It is not the order you wrote.
The second plan, as a tree
A plan tree: orders are hashed and probed by 85 payments, that result is hashed and probed by 201 order lines, and the top hash join produces 216 rows for the count.
Read it from the bottom up. Seq Scan means the whole table is read in order. Each Hash is a build side, the scan above it is the probe side, and the number on the right is how many rows that step really produced.
Three ways to pair rows
A hash join is one of three methods. EXPLAIN names the one Postgres chose.
- Nested loop: for each row on one side, go and find its matches on the other. With an index on the key (a sorted lookup structure, Lesson 2.4) each search is short. Without one, the other table is read again for every row.
- Hash join: build, then probe. The hash table's memory budget is two settings multiplied,
work_memxhash_mem_multiplier: 4 MB x 2.0 = 8 MB by default. A bigger build side is split into batches kept in temporary files. - Merge join: both sides sorted on the key, then walked side by side once.
The method never changes the result. A key repeated on both sides gives every pair in all three.
Three plans for one join
-- a big join with no filter: hash join
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT c.city, SUM(o.amount)
FROM big_orders o
JOIN big_customers c ON c.customer_id = o.customer_id
GROUP BY c.city;
-- ten outer rows: nested loop with an index lookup per row
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT o.order_id, c.name
FROM big_orders o
JOIN big_customers c ON c.customer_id = o.customer_id
WHERE o.order_id <= 10;
-- forbid the other two (for learning only) to see a merge join
SET enable_hashjoin = off;
SET enable_nestloop = off;
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT c.city, SUM(o.amount)
FROM big_orders o
JOIN big_customers c ON c.customer_id = o.customer_id
GROUP BY c.city;
One join, three methods. With no filter, a hash join: it holds 5,000 customers in Buckets: 8192 Batches: 1 Memory Usage: 212kB. With ten orders, a nested loop: its index scan runs loops=10 times. The merge join reads customers in key order from the primary key and sorts 100,000 orders, on disk here. The kB figures come from this browser's 32-bit Postgres; a 64-bit server prints larger ones.
Why NOT EXISTS gets the fast plan
Back to the anti-join, with what you now know.
Postgres runs NOT EXISTS as a Hash Anti Join: each customer probes a hash table of orders and is kept when nothing matches. One pass, one lookup per row.
NOT IN cannot be run that way. If its subquery returns a single NULL, it must return no rows at all, and an anti-join has no way to say that. So it stays a filter against a hashed copy of the subquery. Without enough memory for that hash, Postgres rescans the subquery for every row.
The two questions look the same. Their plans do not.
How the planner sees each anti-join
EXPLAIN (COSTS OFF)
SELECT c.customer_id
FROM customers c
WHERE NOT EXISTS (
SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id
);
EXPLAIN (COSTS OFF)
SELECT c.customer_id
FROM customers c
WHERE c.customer_id NOT IN (SELECT customer_id FROM orders);
The first plan is a Hash Anti Join. The second is a Seq Scan with a Filter on a hashed SubPlan. LEFT JOIN ... WHERE o.customer_id IS NULL also plans as an anti-join here. Test the join key itself: a NULL test on another column of o leaves a Hash Right Join plus a filter.
The trap: NOT IN with a NULL returns nothing. WHERE customer_id NOT IN (SELECT user_id FROM events) returns zero rows, because one NULL in the list makes every comparison unknown. Use NOT EXISTS or LEFT JOIN ... IS NULL. And never "fix" a fan-out with SELECT DISTINCT: it hides the copied rows, and the sums underneath are still wrong.
Numbers to remember
| What | Number or name | What it means |
|---|---|---|
| workmem | 4 MB by default | The memory one sort or one hash may use before it goes to disk |
| hashmemmultiplier | 2.0 by default (since Postgres 15) | A hash table may use workmem times this: 4 MB x 2.0 = 8 MB |
| Batches in a Hash line | 1 when it fits, otherwise a power of two | The build side did not fit, so it was split: one batch stays in memory, the others wait in temporary files |
| Nested loop in EXPLAIN | Nested Loop, inner line with loops=N | Wins with few outer rows and an indexed inner side. The only method for a join on <, or BETWEEN |
| Hash join in EXPLAIN | Hash Join over Hash, with Buckets, Batches, Memory Usage | Needs an = condition. Wins on big unsorted inputs when one side is small enough to hash |
| Merge join in EXPLAIN | Merge Join over Sort or Index Scan lines | Needs = and both inputs sorted on the key. Wins when indexes already give the order, or both sides are too big to hash |
| Nested loop, no index, 100,000 orders x 5,000 customers | 500 million pairs compared | The inner table is read again for every outer row |
| The same join with the customers primary key | 100,000 lookups: 2 index pages and 1 table page each | 5,000 keys fit in a root page and 14 leaf pages |
| The same join as a hash join | 1 read of customers, 100,000 probes | A 5,000-entry hash table, built once |
A page is one fixed-size block of a table or an index on disk. Lessons 2.4 and 2.8 come back to pages.
What changed at SwiftKart
You rewrite the revenue query: lines summed per order, captured payments summed per order, then joined one to one. It returns 80 rows and $8,514.73. Tess's number and the payments table agree again.
You keep two habits. Count the rows before and after every join. And when someone asks "what is missing?", write an anti-join with NOT EXISTS. It already found two orders to ask Dana about: 1047 and 1058.
Tess has a second puzzle. Three dashboards say SwiftKart has 30, 29 and 27 customers. Lesson 2.2 picks that up: what COUNT really counts, and what GROUP BY does to the grain.
In one line
A join copies rows when its key repeats, so sum each child table to one row per order before joining, find missing rows with NOT EXISTS, and count before and after.
Interview corner
Revenue doubled after you added a join. What happened, and how do you fix it?
The join fanned out: a table at a finer grain (order lines, or several payments per order) copied each parent row, so a parent-level amount was summed once per copy. I would check row counts before and after the join, then aggregate the child table to one row per parent in a CTE before joining, so every join is one-to-one.
What is the difference between NOT IN, NOT EXISTS and LEFT JOIN ... IS NULL?
All three find rows with no match, but NOT IN returns nothing if the subquery yields a single NULL, because the comparison becomes unknown. NOT EXISTS and LEFT JOIN ... WHERE right.key IS NULL handle NULLs correctly, and planners usually run them the same way. I default to NOT EXISTS for clarity.
How do you make sure a join did not drop or duplicate rows?
Know the grain of both sides and whether the key is unique on the right. Then compare COUNT(*) before and after, and COUNT(*) with COUNT(DISTINCT key) after. In a pipeline these become automated tests, such as a dbt unique test on the model key and a relationships test for orphans.
How does Postgres choose between a nested loop, a hash join and a merge join?
By estimated cost, from the row estimates in its statistics. A nested loop wins when few outer rows remain and the inner side has an index: ten orders mean ten index lookups. A hash join wins for big unsorted inputs: it builds a hash table on the smaller side within work_mem x hash_mem_multiplier (8 MB by default) and splits it into on-disk batches when it is bigger. A merge join wins when both inputs already come sorted, for example from indexes; only a nested loop can do a join on < or BETWEEN.