QA Interview Hub · Knowledge base · Quizzes · Українська

SQL › JOIN

Why did the row count grow after a JOIN and the sum double?

After a one-to-many JOIN the parent row is repeated once per pair, so sums over its columns are inflated. This shows when COUNT(*) is larger than COUNT(DISTINCT key). SUM(DISTINCT) does not fix it: it removes equal values, not duplicated orders. The child table is collapsed to one row per parent before the join.

SQL · JOIN

Revenue in the report is 150 and the orders table says 100. Nothing changed, a JOIN to payments was only added.

A join with payments was added to a query about orders to show how much is already paid. The sum of orders grew from 100 to 150. Nothing changed in the data and there is no error. The rows multiplied: one order had two payments and landed in the result twice. This lesson is about row multiplication (fan-out), how to notice it, why SUM(DISTINCT) does not save you and how to restructure the query. How this looks from the tester's side in reports is covered in the QA Fundamentals lesson on kinds of JOIN; here the mechanics go deeper.

How it works and why. JOIN outputs one row per pair. If the link is one-to-many (one order, several payments), the left row repeats as many times as it has pairs. The values in the repeats do not change, so every column of the left table counts as many times as there are pairs. SUM, COUNT and AVG over such a column are distorted. An aggregate is safe only for columns of the level that matches the finest table in the query. Hence the rule: aggregate at the level where each value occurs once.

Example: why 150. Orders: 100 (50), 101 (30), 102 (20). Payments: p1 (order 100, 25), p2 (order 100, 25), p3 (order 101, 30). The query:

-- total of orders: the table says 100
SELECT SUM(o.total) AS revenue
FROM orders o
LEFT JOIN payments p ON p.order_id = o.id;
-- 150: order 100 is counted twice

The result is 150: the row of order 100 is repeated twice (50 + 50), 101 once, and 102 once thanks to the LEFT JOIN. The true sum is 100. Diagnostics do not rely on guesses: they compare the row count with the number of distinct keys and find what multiplies:

-- how many rows and how many distinct orders
SELECT COUNT(*) AS rows_cnt, COUNT(DISTINCT o.id) AS orders_cnt
FROM orders o
LEFT JOIN payments p ON p.order_id = o.id;
-- 4 and 3: the link multiplies rows

-- who multiplies
SELECT order_id, COUNT(*) AS pay_cnt
FROM payments
GROUP BY order_id
HAVING COUNT(*) > 1;

How payments multiplied the orders

payments
idorder_idamount
p110025
p210025
p310130
orders LEFT JOIN payments
ordertotalpayment
10050p1
10050p2
10130p3
10220NULL
Figure 1. Order 100 has two payments, so its total 50 enters the result twice.

The fix depends on the question. If you need the sums of orders and payments together, first collapse payments to one row per order and then join:

-- first collapse payments to one row per order
SELECT SUM(o.total) AS revenue,
       SUM(COALESCE(p.paid, 0)) AS paid
FROM orders o
LEFT JOIN (
  SELECT order_id, SUM(amount) AS paid
  FROM payments
  GROUP BY order_id
) p ON p.order_id = o.id;
-- revenue 100, paid 80

Here each order occurs once, so SUM(o.total) gives 100 and the paid amount is 80. A second option, when payment sums are not needed: do not join at all and check that a payment exists with EXISTS. That does not multiply rows by definition.

Limits and alternatives. The temptation: SUM(DISTINCT o.total). On our set it gives 100 and looks like a fix, but only by coincidence: DISTINCT deduplicates values, not orders. If two different orders have the same amount 50, one of them vanishes and the sum is understated. COUNT(DISTINCT o.total) makes the same mistake. The right way is to deduplicate by key (COUNT(DISTINCT o.id) is safe), but that does not work for sums, so collapsing before the join or a subquery is needed. In PostgreSQL and MySQL 8 a CTE or a derived table fits. Another option: a scalar subquery in SELECT (SELECT SUM(amount) FROM payments p WHERE p.order_id = o.id) sums payments per order without a JOIN, so rows do not multiply.

An aggregate before and after the JOIN

Typical

JOIN, then SUM

Each left row repeats by the number of pairs. The sum is 150 instead of 100.

Better

collapse, then JOIN

Payments are reduced to one row per order. The sum is 100, payments separately 80.

Figure 2. Aggregate at the level where values do not repeat, and only then join.

A separate form of the problem is two one-to-many links in one query: an order with payments and with shipments. Each order produces a product of pairs "payment × shipment", so both payment sums and shipment sums are overstated. The cure is the same: collapse each "child" set on its own.

Common mistakes.

  • Aggregating a parent table column after a one-to-many JOIN: sums are overstated.
  • SUM(DISTINCT) as a "fix": it works on test data with different values and breaks when two amounts coincide.
  • Not comparing COUNT(*) with COUNT(DISTINCT key) after the join: the multiplication is invisible.
  • Joining two child tables to a parent in one query without collapsing: a product of pairs.
  • Believing the sum in a report is right because it looks plausible: a coincidence of two errors (a duplicate and a lost row) can produce the right number.

Check yourself

orders has 3 orders of 100 each and each has two payments. What does SUM(o.total) return after an INNER JOIN payments and why would SUM(DISTINCT o.total) give 100 here?

Answer

SUM(o.total) = 600, because each of the 3 orders is counted twice. SUM(DISTINCT o.total) = 100, because all three amounts are equal and DISTINCT keeps one value, while the real sum is 300. So DISTINCT gives a wrong result in the opposite direction.

How can one query tell you whether a JOIN multiplies rows, without knowing the schema?

Answer

Compare SELECT COUNT(*) with SELECT COUNT(DISTINCT o.id) for the same join (o is the left side). If the first number is bigger, the left row repeats. Find the source by grouping the right table by the link key with HAVING COUNT(*) > 1.

In an interview. Junior: In a one-to-many link each row of the "one" side repeats as many times as it has pairs, so sums over its columns after a JOIN are overstated. You must aggregate before the join or aggregate from the table where each value occurs once. Middle/Senior: Before an aggregate after a JOIN I compare COUNT(*) with COUNT(DISTINCT key) and look at the uniqueness of the join key. I collapse a child set in a subquery or CTE to one row per parent. I do not treat SUM(DISTINCT) as a fix: it deduplicates values, not rows.

More articles in this chapter