Why is my SUM too high after a JOIN?
Your SUM is too high because the JOIN repeated some rows. A join returns one row for every match, so an order with three items shows up three times, and SUM adds its total three times. To fix it, add up the table with many rows first, then join.
How it usually happens
You have a query that returns revenue, and the number is right. Then someone asks for one more column: how many items were sold. The items live in another table, so you join it and add a COUNT. The query runs with no error, and revenue has doubled. Nobody touched the SUM.
The tables
| order_id | customer | total |
|---|---|---|
| 1 | Ana | 50 |
| 2 | Ben | 20 |
| 3 | Ana | 30 |
| item_id | order_id | product |
|---|---|---|
| 1 | 1 | Beans |
| 2 | 1 | Mug |
| 3 | 1 | Filter |
| 4 | 2 | Beans |
| 5 | 3 | Mug |
Three orders, worth 100 in total. Order 1 has three items.
The query with the wrong total
SELECT SUM(o.total) AS revenue,
COUNT(i.item_id) AS items_sold
FROM orders o
JOIN order_items i ON i.order_id = o.order_id;
| revenue | items_sold |
|---|---|
| 200 | 5 |
Five items is right. Revenue should be 100, not 200.
What the join returns before the sum
| order_id | total | product |
|---|---|---|
| 1 | 50 | Beans |
| 1 | 50 | Mug |
| 1 | 50 | Filter |
| 2 | 20 | Beans |
| 3 | 30 | Mug |
Order 1 is there three times, once per item, and its total of 50 comes along each time. SUM adds 50 + 50 + 50 + 20 + 30.
The fix
Count the items per order first, so there is one row per order again. Then join.
SELECT SUM(o.total) AS revenue,
SUM(i.items) AS items_sold
FROM orders o
JOIN (
SELECT order_id, COUNT(*) AS items
FROM order_items
GROUP BY order_id
) i ON i.order_id = o.order_id;
| revenue | items_sold |
|---|---|
| 100 | 5 |
Rule to remember: before you sum a column after a join, check that each row you are summing still appears once. A quick test is to count the rows before and after the join. Here it goes from 3 to 5, and that is the warning.
Try it yourself
Same trap, different tables. An agency sends invoices, and clients sometimes pay one invoice in two parts.
| invoice_id | client | amount |
|---|---|---|
| 1 | Acme | 500 |
| 2 | Birch | 200 |
| 3 | Acme | 300 |
| payment_id | invoice_id | paid |
|---|---|---|
| 1 | 1 | 200 |
| 2 | 1 | 300 |
| 3 | 2 | 200 |
| 4 | 3 | 100 |
The query below is meant to show each client with the total billed and the total paid, sorted by client. It says Acme was billed 1300, and the real number is 800. Fix it.
Hint
Invoice 1 was paid in two parts. How many times does its amount get added?
Show solution
SELECT i.client, SUM(i.amount) AS billed, SUM(p.paid) AS paid
FROM invoices i
JOIN (
SELECT invoice_id, SUM(paid) AS paid
FROM payments
GROUP BY invoice_id
) p ON p.invoice_id = i.invoice_id
GROUP BY i.client
ORDER BY i.client;| client | billed | paid |
|---|---|---|
| Acme | 800 | 600 |
| Birch | 200 | 200 |
MintQuery has 500+ exercises like this one, in lessons of a few minutes.
Start freeGet the app