Quick revision
The short answer
Joining orders to both order_lines and payments multiplies rows: an order with 3 lines and 2 payments becomes 6 joined rows, so SUM(orders.total) counts that order's total 6 times. The fix is to aggregate each child table separately, in its own subquery or CTE grouped by order_id, and join those one-row-per-order results to orders. SUM(DISTINCT) is not a fix, because two genuine equal amounts would collapse.
What to remember
In this answer, we saw that joining an order to both lines and payments produces every combination of the two, so the order total is counted lines x payments times and each payment once per line. Aggregating each child table by order_id in its own CTE and joining the results keeps every join one-to-one and the sums correct. COUNT(DISTINCT) can fix counts, but SUM(DISTINCT) collapses genuine equal amounts. Counting rows after each join and reconciling a couple of orders by hand catch fan-out before a report ships.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Joining orders to both order_lines and payments multiplies rows: an order with 3 lines and 2 payments becomes 6 joined rows, so SUM(orders.total) counts that order's total 6 times. The fix is to aggregate each child table separately, in its own subquery or CTE grouped by order_id, and join those one-row-per-order results to orders. SUM(DISTINCT) is not a fix, because two genuine equal amounts would collapse.
Why this question is asked
Inflated totals in a report are one of the most expensive SQL bugs, because the numbers look plausible until finance compares them with the ledger. The cause here is a fan-out, where joining one parent to two independent child tables produces every combination of children. Interviewers ask this to see whether we can explain the multiplication precisely, fix it in a way that is correct by construction, and recognise the tempting fixes that are wrong. In this answer, we will reproduce the problem with one order, see exactly where the multiplication comes from, fix it with pre-aggregation, look at why DISTINCT tricks fail, and finish with a habit for catching fan-out early.
1Reproducing the Problem With One Order
Order 1 has a total of 100.00. It has three order lines and was paid in two payments of 60.00 and 40.00. The report joins everything and sums.
The order total is six times too high and the paid amount three times too high. Across a whole report, where some orders have one line and one payment and others have many, the error averages out to the two to three times inflation that was observed, which also explains why it was not obvious at first glance.
2Where the Multiplication Comes From
Each join returns one row per matching pair. Joining order 1 to its 3 lines gives 3 rows. Joining each of those rows to the 2 payments gives 3 x 2 = 6 rows. Lines and payments have nothing to do with each other, so the database produces every combination of them: line 1 with payment A, line 1 with payment B, line 2 with payment A, and so on. This is often called fan-out, or a chasm trap when two independent children hang off one parent.
| order total | line | payment |
|---|---|---|
| 100.00 | line 1 | A: 60.00 |
| 100.00 | line 1 | B: 40.00 |
| 100.00 | line 2 | A: 60.00 |
| 100.00 | line 2 | B: 40.00 |
| 100.00 | line 3 | A: 60.00 |
| 100.00 | line 3 | B: 40.00 |
SUM(total) = 600.00 (6 copies); SUM(amount) = 300.00 (each payment 3 times, once per line).Every column of a joined row is repeated for each combination, so any SUM over the parent's columns is multiplied by lines x payments, and any SUM over one child's columns is multiplied by the number of rows in the other child. COUNT(*) is wrong too: it counts 6.
3The Fix: Aggregate Each Child Separately, Then Join
The rule that keeps joins safe for aggregation is to join tables at the same grain. Grain means what one row represents. orders has one row per order; order_lines and payments have many rows per order. If we reduce each child to one row per order first, all three inputs have the same grain and the joins cannot multiply anything.
Each CTE produces at most one row per order, so every join is one-to-one. The order total comes straight from orders, read once. LEFT JOINs keep orders that have no payments yet, and COALESCE shows 0 instead of NULL. For a report summed over all orders, we wrap this in an outer SUM(o.total), SUM(ps.paid), which is now safe.
If the report only needs order totals and payment sums, we can drop the lines CTE entirely. Joining a table we do not need is the most common way fan-out sneaks in.
4Why DISTINCT Tricks Do Not Fix It
Two shortcuts are often tried. COUNT(DISTINCT l.id) does fix counts, because each line has a unique id and DISTINCT removes the repeats. That is legitimate for counting.
SUM(DISTINCT o.total) looks similar but is wrong. DISTINCT applies to the values being summed, not to the rows they came from. If two different orders both have a total of 100.00, the sum across them counts 100.00 only once, so the report is now too low instead of too high. The same happens with payments: two genuine payments of 50.00 on one order collapse into one. The numbers might even look right on a small test set where amounts happen to be different, which makes this fix particularly dangerous. Pre-aggregation is correct by construction; DISTINCT is correct only by luck.
5Catching Fan-Out Early
The habit that catches this is checking row counts at each join step while building a report. Count the rows of the base table for the report's filter, then add one join at a time and count again. If adding a join to a table that should be one-to-one changes the count, or adding a one-to-many join changes it more than expected, there is fan-out. A quick check is SELECT COUNT(*), COUNT(DISTINCT o.id) on the joined result: if the two differ, each order appears more than once and any sum of order columns is inflated.
Reconciling one or two orders by hand against the source tables, as we did with order 1, is the other cheap test before a report goes to finance.
- Count base rowsorders in the report range: 10,000
- Add one join, count againorders + payments: 12,400
- Count grew on a one-to-many join?Yesaggregate that child firstNojoin is safe
- Reconcile two orders by handagainst source tables
4 steps in order. Play them, or step through them one at a time.
6Follow-up questions
Can window functions help instead of CTEs?
They can compute per-order sums without collapsing rows, but the joined rows are still multiplied, so a later SUM over them is still inflated. Aggregating children before the join is clearer and cheaper.
Is a correlated subquery in SELECT an option?
Yes. SELECT o.id, o.total, (SELECT SUM(amount) FROM payments p WHERE p.order_id = o.id) AS paid FROM orders o is correct, because each subquery returns one value per order. It is fine for small result sets; for large reports, the grouped CTE is usually planned more efficiently as a single hash aggregate.
Does this happen in JPA as well?
Yes, when an entity query fetch-joins two collections, such as lines and payments, the SQL produces the same product of rows. Hibernate refuses to fetch two bags at once for this reason, and even with sets the transferred rows multiply. Load the second collection in a separate query.
7Conclusion
In this answer, we saw that joining an order to both lines and payments produces every combination of the two, so the order total is counted lines x payments times and each payment once per line. Aggregating each child table by order_id in its own CTE and joining the results keeps every join one-to-one and the sums correct. COUNT(DISTINCT) can fix counts, but SUM(DISTINCT) collapses genuine equal amounts. Counting rows after each join and reconciling a couple of orders by hand catch fan-out before a report ships.
Open with
The totals are inflated because of fan-out. An order has many lines and many payments, and those two child tables are independent. When I join orders to order_lines I get one row per line, and when I then join payments I get one row per line and payment combination.
Then, if they want more
An order with three lines and two payments becomes six rows, so SUM of orders.total counts that order six times, and each payment is counted once per line. Averaged across orders with different numbers of children, that gives the two to three times inflation.
The fix is to join things at the same grain: I aggregate each child table separately, in a CTE or subquery grouped by order_id, one for line sums and one for payment sums, and then left join those one-row-per-order results to orders. The order total comes from orders, read once. Every join is one-to-one, so nothing multiplies.
If the report does not need the lines at all, I just remove that join. What I would not do is SUM DISTINCT: DISTINCT applies to values, so two real orders or payments with the same amount collapse into one and the total becomes too low. COUNT DISTINCT on an id is fine for counts.
And when I build such reports, I count rows after each join and reconcile one or two orders by hand, which catches fan-out immediately.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- PostgreSQL documentation, The SQL Language
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "A report joins orders to order_lines and to payments, then sums orders.total. The totals...": https://scrivio-interview-library.netlify.app/databases/sql-joins-and-subqueries/9594524c73/