Tutorial / SQL

When a join multiplies your rows

Intermediate1 min6 Dec 2026

An orders report suddenly shows the same order three times, and the total is triple what the invoices say. The WHERE clause is fine. The join is matching one order to several rows in the other table.

See the multiplication

SQL
SELECT o.id, o.total, p.status
FROM orders AS o
JOIN payments AS p ON p.order_id = o.id
WHERE o.created_at >= '2026-12-01';

If an order has three payment rows, this returns three copies of that order. Summing o.total in the same query counts the money three times.

Aggregate before you join, or group after

Decide what one output row means. If you want one row per order, collapse the payments first, then join.

SQL
SELECT o.id, o.total, pay.payment_count
FROM orders AS o
JOIN (
  SELECT order_id, COUNT(*) AS payment_count
  FROM payments
  GROUP BY order_id
) AS pay ON pay.order_id = o.id;
  • Count the rows before and after the join. A jump means the key is not one-to-one.
  • Never SUM a column from the parent table after a one-to-many join.
  • Put the unique key in the ON clause, not in the WHERE clause, so the relationship stays obvious.

Related