Joins · Problem 54 of 118

The Fan-Out Trap

HardJoinsShop data

For orders 2 to 9 (each has exactly one payment), return order_id, items_total (sum of quantity * unit_price over its lines, rounded to 2 decimals) and paid (the payment amount). Sort by order_id.

Beware: an order can have several lines but only one payment.

Hint 1

If you join orders, order_items and payments in one go, the payment row is repeated for every order line.

Hint 2

Summarise the lines per order first (in a subquery or a CTE), then join that summary to the payment.

Reference solution

WITH lines AS (
  SELECT order_id, ROUND(SUM(quantity * unit_price), 2) AS items_total
  FROM order_items
  GROUP BY order_id
)
SELECT l.order_id, l.items_total, p.amount AS paid
FROM lines AS l
JOIN payments AS p ON p.order_id = l.order_id
WHERE l.order_id BETWEEN 2 AND 9
ORDER BY l.order_id;

A join produces one row for each pair of matching rows. An order with 3 lines and 1 payment gives 3 joined rows, so summing the payment over them counts it 3 times. This fan-out inflates totals without any error message, and it is behind a large share of wrong dashboards. The cure: reduce each side to one row per join key (aggregate first), and only then join. The summary is then a one-to-one match.

Another way. A correlated subquery per payment: slower on big tables, but it cannot multiply rows.

SELECT p.order_id,
       (SELECT ROUND(SUM(quantity * unit_price), 2) FROM order_items AS oi WHERE oi.order_id = p.order_id) AS items_total,
       p.amount AS paid
FROM payments AS p
WHERE p.order_id BETWEEN 2 AND 9
ORDER BY p.order_id;