Why did my JOIN multiply the rows?
A join returns one row for every pair of rows whose keys match. If a key appears twice on one side, every match with it appears twice, and any total built on top of it counts those rows twice.
This page uses the script from Step through a SQL query, with one change: customer 1 was loaded into customers twice.
INSERT INTO customers VALUES
(1, 'Ava Brooks', 'North'),
(1, 'Ava Brooks', 'North'),
(2, 'Ben Okafor', 'South'),
...
1. Spot the wrong number
Load the script and choose Run. The result now says North had 5 orders and 424.49 in revenue. Without the extra row it is 3 orders and 262.24.
The join's box gives a hint too: it matched 9 records, but there are only 7 completed orders.
2. Trace the row
Open the North row's provenance, as in Trace a result row back to its source rows. 3 orders went into the join and 5 records came out.
Click Join_1 in the panel. Orders 120.00 and 42.25 are each there twice.
3. Find the duplicate
Click customers in the panel. It lists three rows, and two of them are customer 1. Each of customer 1's orders matched both, so each was counted twice.
4. Fix it
The best fix is in the data: remove the extra row from customers. If you cannot change the table, join a list with each customer once instead:
SELECT c.region, COUNT(*) AS order_count, SUM(o.amount) AS revenue
FROM orders o
JOIN (SELECT DISTINCT customer_id, region FROM customers) c ON c.customer_id = o.customer_id
WHERE o.status = 'completed'
GROUP BY c.region
ORDER BY revenue DESC;
The DISTINCT becomes its own step, Distinct_1, which turns the 7 customer rows into 6. The join matches 7 records again, and North is back to 3 orders and 262.24.
DISTINCT only helps when the duplicate rows are the same in every column you select. If the two copies differ, for example a customer listed under two regions, decide which one is right and fix the table.
Try it
The Revenue by Region example is the same kind of query, with the filter as its own step.
Open the Revenue by Region example