DOTTY

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.

The completed run: Join_1 matched 9, and Sort_1's output shows North 5 424.49, South 2 225.50, East 2 82.75.

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.

The Provenance panel with Join_1 selected: orders 3 and customers 3 feed Join_1 5, and the join's rows list 120.00 and 42.25 twice each, then 99.99 once.

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.

The Provenance panel with customers selected: rows 1 and 2 are both customer 1, North, and row 5 is customer 4, North.

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.

The fixed dataflow: customers, Transform_2 and Distinct_1 with 6 groups feed Join_1, which matched 7; Sort_1's output shows North 3 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

Next: Convert Oracle CONNECT BY to WITH RECURSIVE.