MintQueryStart free
← All guides

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

orders
order_idcustomertotal
1Ana50
2Ben20
3Ana30
order_items
item_idorder_idproduct
11Beans
21Mug
31Filter
42Beans
53Mug

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;
revenueitems_sold
2005

Five items is right. Revenue should be 100, not 200.

What the join returns before the sum

order_idtotalproduct
150Beans
150Mug
150Filter
220Beans
330Mug

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;
revenueitems_sold
1005

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.

invoices
invoice_idclientamount
1Acme500
2Birch200
3Acme300
payments
payment_idinvoice_idpaid
11200
21300
32200
43100

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;
clientbilledpaid
Acme800600
Birch200200

MintQuery has 500+ exercises like this one, in lessons of a few minutes.

Start freeGet the app