← Learn SQL

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.

intermediate#sql#intermediate#joins#left-join#grain#fan-out#sum-distinct

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:

See here how to connect with CloudBeaver, and how to run the koans

LEFT JOIN, then JOIN: 7 rows of 10

Mnemosyne, questioning
Mnemosyne

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.

Leo, excited
Leo

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.

Mnemosyne, pointing-right
Mnemosyne

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";
Leo, smiling-eyes-open
Leo

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.

ProductName
May units
Coastal Parmesan
10
Harvest Butter
408
Heritage Butter
836
Heritage Gouda
58
Highland Yoghurt
52
Rustic Butter
471
Smoked Feta
56
Leo, surprised
Leo

Seven rows? I expected ten — ten products went in.

Mnemosyne, questioning
Mnemosyne

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.

Leo, surprised
Leo

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?

Mnemosyne, questioning
Mnemosyne

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

Leo, proud
Leo

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";
10 rows — and the units add up to 109446
ProductName
May units
Alpine Butter
1819
Classic Feta
2991
Coastal Parmesan
1759
Harvest Butter
20002
Heritage Butter
47743
Heritage Gouda
1562
Highland Yoghurt
2107
Island Cheddar
3436
Rustic Butter
26813
Smoked Feta
1214
Mnemosyne, questioning
Mnemosyne

All ten products are back. Now read Heritage Butter.

Leo, surprised
Leo

Wait — 47743 units in May? Two minutes ago it was 836.

Mnemosyne, questioning
Mnemosyne

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.

Leo, surprised
Leo

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

Mnemosyne, questioning
Mnemosyne

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";
Leo, thinking
Leo

So the month of May is filtered inside the brackets, before the join — and the join can't drop any product.

ProductName
May units
Alpine Butter
[NULL]
Classic Feta
[NULL]
Coastal Parmesan
10
Harvest Butter
408
Heritage Butter
836
Heritage Gouda
58
Highland Yoghurt
52
Island Cheddar
[NULL]
Rustic Butter
471
Smoked Feta
56
Mnemosyne, proud
Mnemosyne

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.

Leo, excited
Leo

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

Mnemosyne, questioning
Mnemosyne

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;
Leo, excited
Leo

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.

CompanyName
Total sales
Freight
Quayside Wholefoods
3102.87
3409.7
Nordic Foods
11322.73
3295.76
Golden Pantry
18342.33
2414.54
Emerald Grocers
2744.71
1951.72
Alpine Provisions
15686.56
1814.54
Leo, proud
Leo

Quayside Wholefoods pays the most freight: 3409.7.

Mnemosyne, questioning
Mnemosyne

On 3102.87 of sales, Leo. Read the row again. They paid more to ship the goods than the goods were worth.

Leo, thinking
Leo

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;
CompanyName
Freight
Baltic Supermarket
752.27
Golden Pantry
744.17
Nordic Foods
709.59
Alpine Provisions
610.83
Quayside Wholefoods
571.5
Mnemosyne, questioning
Mnemosyne

Compare it with the report that joined the order lines. Which one is right?

Leo, excited
Leo

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

Mnemosyne, pointing-right
Mnemosyne

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";
Leo, thinking
Leo

So I group by the order, and count star gives the number of lines in each.

OrderID
Freight
Lines
8415
3.86
1
8472
567.64
6
Leo, thinking
Leo

Order 8415 has one line — and 8472 has six.

"Orders" joined to "Order Details": 2 May orders, 7 lines

OrderRowFreight
8415line 13.86
8472line 1567.64
8472line 2567.64
8472line 3567.64
8472line 4567.64
8472line 5567.64
8472line 6567.64

Freight in the answer: 3409.7 · each freight counted once: 571.5

Mnemosyne, questioning
Mnemosyne

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.

Leo, thinking
Leo

So two orders beat Baltic Supermarket's five. The more lines, the more freight.

Mnemosyne, shrugging
Mnemosyne

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";
Orders alone
After the join
693052.88
2161332.75
Leo, surprised
Leo

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

Leo, proud
Leo

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";
SUM(DISTINCT)
566293.15
Mnemosyne, questioning
Mnemosyne

Careful, Leo — it's smaller, yes, but still wrong: 126759.73 short of the real 693052.88. DISTINCT removes repeated values, not repeated orders.

Leo, surprised
Leo

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";
Orders
Freight values
10000
6960

Aggregate first, then join

Mnemosyne, talking
Mnemosyne

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;
CompanyName
Total sales
Freight
Baltic Supermarket
9445.2
752.27
Golden Pantry
18342.33
744.17
Nordic Foods
11322.73
709.59
Alpine Provisions
15686.56
610.83
Quayside Wholefoods
3102.87
571.5
Mnemosyne, proud
Mnemosyne

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.

Leo, smiling-eyes-open
Leo

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

Mnemosyne, questioning
Mnemosyne

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.

Leo, thinking
Leo

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?

Mnemosyne, questioning
Mnemosyne

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.

Leo, smiling-eyes-open
Leo

"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;
Lines
Customers
779
78
Mnemosyne, pointing-right
Mnemosyne

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?

Leo, thinking
Leo

Mnemosyne, before we finish, may I come back to my case?

Mnemosyne, questioning
Mnemosyne

Of course. First, remind us what we know so far.

Leo, thinking
Leo

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.

Mnemosyne, questioning
Mnemosyne

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.

Leo, thinking
Leo

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;
Mnemosyne, smiling-eyes-open
Mnemosyne

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.

Orders
Value
178
257319.65
Leo, thinking
Leo

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.

Mnemosyne, smiling-eyes-open
Mnemosyne

Good, Leo — you counted DISTINCT orders. Each row here is one line, so count star would have said 429 — lines, not orders.

Leo, thinking
Leo

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.

Mnemosyne, smiling-eyes-open
Mnemosyne

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

Mnemosyne, questioning
Mnemosyne

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.

Leo, smiling-eyes-open
Leo

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

Mnemosyne, excited
Mnemosyne

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.

Leo, excited
Leo

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!

  1. Subqueries — one query's result inside another
  2. CASE — SQL's if/then for labels & buckets
  3. Dates & Times — ranges and boundaries
  4. Multi-Table JOINs & Grain — rows dropped or multiplied (this lesson)
  5. CTEs (WITH) — a long query, in named steps
  6. VIEWs, CREATE TABLE AS & Temp Tables — query or answer
  7. EXISTS & Correlated Subqueries — and the NOT IN trap
  8. Self-JOINs & Hierarchies — rows in the same table
  9. Window Functions I: OVER, PARTITION BY & ROW_NUMBER
  10. String Functions, LIKE & Regex — clean up messy data
  11. Window Functions II: LAG/LEAD, Running Totals & Frames
  12. UNION, INTERSECT, EXCEPT — stack and reconcile lists
  13. GROUPING SETS, ROLLUP & CUBE — subtotals in one pass
  14. INSERT, UPDATE, DELETE & Transactions — safely
  15. UPSERT & MERGE — insert or update, safely re-run
  16. Median and Percentiles — WITHIN GROUP, not AVG
  17. 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