SQL: a JOIN can multiply rows, and SUM will multiply with them

Joining to a one-to-many table repeats the parent's columns once per child. Any aggregate over a parent column then counts it several times, and the total is silently too high.

Code
-- order.total is repeated once per item -> revenue is inflated
SELECT SUM(o.total)
  FROM orders o JOIN order_item i ON i.order_id = o.id;

-- aggregate each side separately
SELECT (SELECT SUM(total) FROM orders)      AS revenue,
       (SELECT COUNT(*)  FROM order_item)   AS items;

-- or de-duplicate before summing
SELECT SUM(total) FROM (
  SELECT DISTINCT o.id, o.total
    FROM orders o JOIN order_item i ON i.order_id = o.id) t;
Output
joined SUM      : 4,182,110    <- wrong, counts each order once per item
separate SUM    :   482,110    <- correct

-- The tell is a revenue figure that is a suspiciously round multiple of the
-- real one - roughly the average number of items per order.
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-08-25