Multi-Table JOINs & Grain — When a Join Silently Drops or Multiplies Your Rows
Catch the join that drops rows a LEFT JOIN should have kept, and the join that multiplies a total, then fix both by narrowing or aggregating before you join.
This article is part of the Learn SQL hands-on course series.
Prerequisite — this is a hands-on lesson. Reading it is not enough. Run every query yourself in CloudBeaver, against the Northwind Company sample database on PostgreSQL — and solve the koans yourself on DuckDB, the same Northwind Company data.
Not set up yet? It only takes a couple of minutes:
LEFT JOIN, then JOIN: 7 rows of 10
Leo, in the last lesson of Series 1, the beginner series, you built your top ten customers report. There, joining the order lines repeated each order once for every line: Alfreds showed 11 orders instead of 5, and count(DISTINCT) on the order ID put it right. Today, two more things a join can do to a report with no error at all: drop rows, and multiply money. First, Dairy: butter, cheese and yoghurt, one of the eight product categories the company has always sold. Every month the Dairy manager checks how many units each of her ten products sold; this time, May 2024. She wants the ones that sold nothing on the list too: those are the products she may stop buying.
All ten, even the ones that sold nothing? Then it's a LEFT JOIN — from our first lesson on JOINs, in Series 1. And May is from 1 May up to, not including, 1 June: the half-open range from our last lesson, on dates and times.
Go on.
SELECT p."ProductName",
sum(d."Quantity") AS "May units"
FROM "Products" p
LEFT JOIN "Order Details" d
ON d."ProductID" = p."ProductID"
JOIN "Orders" o
ON o."OrderID" = d."OrderID"
AND o."OrderDate" >= DATE '2024-05-01'
AND o."OrderDate" < DATE '2024-06-01'
WHERE p."CategoryID" = 4
GROUP BY p."ProductName"
ORDER BY p."ProductName";Products, LEFT JOIN the order lines, then join the orders — the month of May in the ON, and category four, Dairy, in the WHERE. LEFT JOIN at the top, so every product stays. I'm expecting ten rows.
Seven rows? I expected ten — ten products went in.
Right, Leo — your LEFT JOIN kept all ten. Then the plain JOIN to the orders kept only rows that found a May order — and threw the other three away.
So the second join undid the first one — and those three are exactly the products the manager asked about. Is that every inner join after a LEFT JOIN, or did I just get unlucky?
Every one of them. It's the ON-versus-WHERE trap from our first lesson on JOINs, in Series 1, now with a third table: an inner join after a left join drops what the left join kept. And a report like this passes for months — until the month a product sells nothing.
LEFT all the way: ten rows, wrong numbers
Then I'll try making the second join a LEFT JOIN too — if both joins are LEFT, no product can fall out.
SELECT p."ProductName",
sum(d."Quantity") AS "May units"
FROM "Products" p
LEFT JOIN "Order Details" d
ON d."ProductID" = p."ProductID"
LEFT JOIN "Orders" o
ON o."OrderID" = d."OrderID"
AND o."OrderDate" >= DATE '2024-05-01'
AND o."OrderDate" < DATE '2024-06-01'
WHERE p."CategoryID" = 4
GROUP BY p."ProductName"
ORDER BY p."ProductName";All ten products are back. Now read Heritage Butter.
Wait — 47743 units in May? Two minutes ago it was 836.
It isn't May — it's five years. The May test only decides whether an order gets attached; every order line is still there with its quantity. So 47743 is all of Heritage Butter's units, and the ten add up to 109446, against May's real 1891.
With both joins LEFT, I got all ten rows back, Mnemosyne, and I thought I'd fixed it. But now every number in it is wrong: it counts five years of units, not just the month of May.
Narrow first, then join
Narrow first. Add up each product's lines for the month of May in brackets — a table in FROM, from our first lesson of this series, on subqueries — then LEFT JOIN the Dairy products to that.
SELECT p."ProductName",
m."May units"
FROM "Products" p
LEFT JOIN (SELECT d."ProductID",
sum(d."Quantity")
AS "May units"
FROM "Order Details" d
JOIN "Orders" o
ON o."OrderID" = d."OrderID"
WHERE o."OrderDate" >= DATE '2024-05-01'
AND o."OrderDate" < DATE '2024-06-01'
GROUP BY d."ProductID") AS m
ON m."ProductID" = p."ProductID"
WHERE p."CategoryID" = 4
ORDER BY p."ProductName";So the month of May is filtered inside the brackets, before the join — and the join can't drop any product.
It didn't drop any, Leo: ten rows. Seven sold units in May, adding up to 1891; the other three are NULL — no sale in May.
Those three are the ones the manager wanted to see. And Heritage Butter is back to 836.
Your turn, Leo.
How many Dairy products had no sale in May?
Count the NULLs the narrowed-first query leaves. You should get 3.
▶ Continue once you've run it.
SELECT count(*) AS "No May sale"
FROM "Products" p
LEFT JOIN ( … May's lines per product … ) AS m
ON m."ProductID" = p."ProductID"
WHERE p."CategoryID" = 4
AND ___;Sales and freight per customer
Now the join that multiplies money. The next request: sales and freight per customer for May, on one report.
SELECT c."CompanyName",
ROUND(SUM(d."UnitPrice" * d."Quantity"
* (1 - d."Discount")), 2) AS "Total sales",
SUM(o."Freight") AS "Freight"
FROM "Customers" c
JOIN "Orders" o
ON o."CustomerID" = c."CustomerID"
JOIN "Order Details" d
ON d."OrderID" = o."OrderID"
WHERE o."OrderDate" >= DATE '2024-05-01'
AND o."OrderDate" < DATE '2024-06-01'
GROUP BY c."CompanyName"
ORDER BY "Freight" DESC
LIMIT 5;So it's my top ten customers report from Series 1, with one more SUM: I join customers, orders and order lines, keep May, and sort by freight for the top five.
Quayside Wholefoods pays the most freight: 3409.7.
On 3102.87 of sales, Leo. Read the row again. They paid more to ship the goods than the goods were worth.
Hmm... that can't be right. Let me try it another way. Freight is stored on the order, so I'll leave out the order lines: just customers and their orders in May, and the same SUM of freight. One row is one order, so each order's freight is added only once.
SELECT c."CompanyName",
SUM(o."Freight") AS "Freight"
FROM "Customers" c
JOIN "Orders" o
ON o."CustomerID" = c."CustomerID"
WHERE o."OrderDate" >= DATE '2024-05-01'
AND o."OrderDate" < DATE '2024-06-01'
GROUP BY c."CompanyName"
ORDER BY "Freight" DESC
LIMIT 5;Compare it with the report that joined the order lines. Which one is right?
This one — it adds each order's freight once. The real number one is Baltic Supermarket, with 752.27, and it wasn't even in that top five. Quayside Wholefoods paid 571.5: fifth, not first. So the join with Order Details pushed their freight up to 3409.7.
Why the freight grew: copied onto every line
Then let's see where Quayside's 3409.7 came from. They placed two orders in May: one row per order, and count each one's lines.
SELECT o."OrderID", o."Freight",
count(*) AS "Lines"
FROM "Orders" o
JOIN "Order Details" d
ON d."OrderID" = o."OrderID"
WHERE o."CustomerID" = 'QUAY3'
AND o."OrderDate" >= DATE '2024-05-01'
AND o."OrderDate" < DATE '2024-06-01'
GROUP BY o."OrderID", o."Freight"
ORDER BY o."OrderID";So I group by the order, and count star gives the number of lines in each.
Order 8415 has one line — and 8472 has six.
"Orders" joined to "Order Details": 2 May orders, 7 lines
| Order | Row | Freight |
|---|---|---|
| 8415 | line 1 | 3.86 |
| 8472 | line 1 | 567.64 |
| 8472 | line 2 | 567.64 |
| 8472 | line 3 | 567.64 |
| 8472 | line 4 | 567.64 |
| 8472 | line 5 | 567.64 |
| 8472 | line 6 | 567.64 |
Freight in the answer: 3409.7 · each freight counted once: 571.5
Freight is stored once per order. Join the lines and it's copied onto each one: 3.86 once, and 567.64 six times. That's your 3409.7 — almost all of it one order, counted six times.
So two orders beat Baltic Supermarket's five. The more lines, the more freight.
And it isn't only Quayside. The whole company, all five years: 693052.88 of freight from the orders — and 2161332.75 after joining the lines.
SELECT (SELECT SUM("Freight")
FROM "Orders") AS "Orders alone",
(SELECT SUM(o."Freight")
FROM "Orders" o
JOIN "Order Details" d
ON d."OrderID" = o."OrderID")
AS "After the join";More than three times the real bill — and nothing errored. In Series 1, DISTINCT fixed Alfreds' order count; I'll try it on the sum.
SUM(DISTINCT) is no fix
With DISTINCT, the freight comes down to 566293.15 — no more copies.
SELECT SUM(DISTINCT o."Freight")
AS "SUM(DISTINCT)"
FROM "Orders" o
JOIN "Order Details" d
ON d."OrderID" = o."OrderID";Careful, Leo — it's smaller, yes, but still wrong: 126759.73 short of the real 693052.88. DISTINCT removes repeated values, not repeated orders.
Then I'll count them: ten thousand orders, and only 6960 different freight values. So two orders with the same freight counted once — DISTINCT dropped the rest, and that's the missing 126759.73.
SELECT count(*) AS "Orders",
count(DISTINCT "Freight")
AS "Freight values"
FROM "Orders";Aggregate first, then join
So DISTINCT can't fix a sum, Leo. Aggregate first, then join. Sales per customer from the order lines, freight per customer from the orders alone — two tables in brackets, each at its own grain — and only then join them to the customers.
SELECT c."CompanyName", s."Total sales", f."Freight"
FROM "Customers" c
JOIN (SELECT o."CustomerID",
ROUND(SUM(d."UnitPrice" * d."Quantity"
* (1 - d."Discount")), 2) AS "Total sales"
FROM "Orders" o
JOIN "Order Details" d
ON d."OrderID" = o."OrderID"
WHERE o."OrderDate" >= DATE '2024-05-01'
AND o."OrderDate" < DATE '2024-06-01'
GROUP BY o."CustomerID") AS s
ON s."CustomerID" = c."CustomerID"
JOIN (SELECT "CustomerID",
SUM("Freight") AS "Freight"
FROM "Orders"
WHERE "OrderDate" >= DATE '2024-05-01'
AND "OrderDate" < DATE '2024-06-01'
GROUP BY "CustomerID") AS f
ON f."CustomerID" = c."CustomerID"
ORDER BY f."Freight" DESC
LIMIT 5;Baltic Supermarket is first again, with 752.27 — and every sales total is exactly what the joined report said. Quayside Wholefoods' 3102.87 was right all along — next to a freight six times too big.
Both columns right at last. And the May dates are written twice, in a query I can barely read.
Grain: one row = one order line
It's long, Leo, but every number in it is right — each SUM ran where its column lives. So before any SUM after a join, check what one row stands for: one order, or one order line.
After joining the lines, one row is one order line. But freight belongs to one order. So every column at a different grain needs its own query?
Its own step, not its own report. Sum freight where one row is one order, sum sales where one row is one line — and join the two results. That's the grain of each number.
"Order Details" also sits between orders and products. So for Heritage Butter, count star gives me the lines, and count of DISTINCT customer IDs gives me the customers?
SELECT count(*) AS "Lines",
count(DISTINCT o."CustomerID")
AS "Customers"
FROM "Order Details" d
JOIN "Orders" o
ON o."OrderID" = d."OrderID"
WHERE d."ProductID" = 28;Yes: 779 lines, 78 customers. "Order Details" is a bridge table — it joins orders to products, many to many — so always say which one you are counting.
Case file: how much was never invoiced?
Mnemosyne, before we finish, may I come back to my case?
Of course. First, remind us what we know so far.
My manager's note said: in 2024, orders went up, but invoicing went down. In our lesson on CASE expressions, earlier in this series, we found 178 Speedy Express orders marked Shipped, but with no ship date — and an order is only invoiced once its ship date is recorded. The dates lesson showed almost all of them fall between March and the end of August 2024. I said I'd work out how much money they are. The prices are on the order lines, so I'll join the lines in, then the invoices.
Join the lines in, then — the money is on them. But after that join, one row is one line, not one order. Show me the query.
Here it is: orders, their lines, then LEFT JOIN the invoices — and keep the 2024 orders marked shipped where no invoice matched. Each order now comes once per line, so I count DISTINCT order IDs, not rows.
SELECT count(DISTINCT o."OrderID") AS "Orders",
ROUND(SUM(d."UnitPrice" * d."Quantity"
* (1 - d."Discount")), 2) AS "Value"
FROM "Orders" o
JOIN "Order Details" d
ON d."OrderID" = o."OrderID"
LEFT JOIN "Invoices" i
ON i."OrderID" = o."OrderID"
WHERE o."Status" = 'Shipped'
AND o."OrderDate" >= DATE '2024-01-01'
AND o."OrderDate" < DATE '2025-01-01'
AND i."InvoiceID" IS NULL;Right — no brackets needed this time. The prices are on the order lines themselves, so the sum adds each line exactly once. Only the count needed DISTINCT. Run it.
178 orders, marked shipped, with no invoice. Worth 257319.65. And 178 is the number our last lesson, on dates and times, ended on — these are the same orders, priced.
Good, Leo — you counted DISTINCT orders. Each row here is one line, so count star would have said 429 — lines, not orders.
So that's 257319.65 never invoiced, in Northwind Company. They're marked Shipped, but nothing in this data shows the goods reached the customers.
And that decides what happens to the money. If the goods arrived, the customers owe it: send them the invoices. If they didn't, we claim it from Speedy Express. Which orders are which, we work out in a later lesson of this series.
What to take away, and what is next
Four rules. Count the rows before and after every join. An inner join after a left join undoes it. Narrow or aggregate before you join. And sum each column at its own grain — DISTINCT fixes a count, never a sum.
Seven rows that should have been ten, Mnemosyne, and a customer who wasn't number one. Both from joins I'd have trusted.
Your turn, Leo.
▶ Walk the path to enlightenment.
cd c:/DataPallas/db/datazeus
.\zeus.bat koans learnsql series2 _15- count the rows after the join: Jonas's orders become lines
- diagnose: an INNER JOIN after a LEFT JOIN drops categories
- predict: LEFT all the way looks repaired
- …and seven more, ending with two you write yourself
…/learnsql/series2/_15/MultiTableJoinsDuplicateRowsKoans.groovy
That was multi-table joins, Leo. Count the rows at every join, narrow before you join, and sum each column where it lives. Next lesson: CTEs. WITH gives each step of a query a name, so it reads top to bottom — so the May dates are written once, not twice as in today's freight report.
So the freight report becomes named steps: first the orders placed in May, then sales and freight per customer, then the report itself. Right now all of it sits inside brackets, in one long query.
That's all, folks!
- Subqueries — one query's result inside another
- CASE — SQL's if/then for labels & buckets
- Dates & Times — ranges and boundaries
- Multi-Table JOINs & Grain — rows dropped or multiplied (this lesson)
- CTEs (WITH) — a long query, in named steps
- VIEWs, CREATE TABLE AS & Temp Tables — query or answer
- EXISTS & Correlated Subqueries — and the NOT IN trap
- Self-JOINs & Hierarchies — rows in the same table
- Window Functions I: OVER, PARTITION BY & ROW_NUMBER
- String Functions, LIKE & Regex — clean up messy data
- Window Functions II: LAG/LEAD, Running Totals & Frames
- UNION, INTERSECT, EXCEPT — stack and reconcile lists
- GROUPING SETS, ROLLUP & CUBE — subtotals in one pass
- INSERT, UPDATE, DELETE & Transactions — safely
- UPSERT & MERGE — insert or update, safely re-run
- Median and Percentiles — WITHIN GROUP, not AVG
- Subqueries + CTEs + Window Functions — a real case
Found this to be a little gem? Help others find it too — someone out there is stuck trying to learn SQL right now. The button opens Reddit with the link and title already filled in, so you just pick a community and post.
Share on Reddit