Video in progress

After two JOINs, `SUM(amount)` came out several times larger than the real value. Why, and how do you fix it?

SELECT o.id,
       sum(i.price * i.qty) AS items_total,
       sum(p.amount)        AS paid_total
FROM orders o
JOIN order_items i ON i.order_id = o.id
JOIN payments    p ON p.order_id = o.id
GROUP BY o.id;

This is fan-out: if one order has 3 items and 2 payments, the JOIN produces 6 rows and each amount is added several times. You have to aggregate each "many" side separately and then JOIN.

📖 Answer

Take one order: 3 items, 2 payments. orders × items × payments is 1 × 3 × 2 = 6 rows. Each item amount is added twice, and each payment three times. The result is wrong, but there's no error, and that's the dangerous part.

The right way is to first total each "many" side on its own:

SELECT o.id,
       COALESCE(i.items_total, 0) AS items_total,
       COALESCE(p.paid_total, 0)  AS paid_total
FROM orders o
LEFT JOIN (
    SELECT order_id, sum(price * qty) AS items_total
    FROM order_items GROUP BY order_id
) i ON i.order_id = o.id
LEFT JOIN (
    SELECT order_id, sum(amount) AS paid_total
    FROM payments GROUP BY order_id
) p ON p.order_id = o.id;

Or with correlated subqueries: if only a few orders are selected, that works well too.

"Fixing" it with sum(DISTINCT p.amount) is wrong: two payments with the same amount collapse into one.

To prevent a bug like this, I compare report queries against a result computed by hand on test data, especially when there are several one-to-many JOINs. It's the same in Hibernate: doing JOIN FETCH on two collections at once gives a Cartesian product.