01 / 20

Join Duplication
Issues in SQL

Understand why joins can silently multiply your rows, inflate aggregates like SUM and COUNT, and learn how to detect and fix these hidden bugs.

SQL

What Is a Join?

A JOIN combines rows from two or more tables based on a related column. For every row in the left table, the database finds all matching rows in the right table and pairs them together.

orders order_id cust_id 101 1 102 1 103 2 JOIN ON customers cust_id name 1 Alice 2 Bob

When Joins Go Wrong

Duplication happens when one row in the left table matches multiple rows in the right table. The database creates a separate output row for every combination: this is the many-to-many or one-to-many fan-out.

orders id cust_id 101 1 payments id order_id P1 101 P2 101 Result: 2 rows from 1 order (duplicated!) order: 101, payment: P1 order: 101, payment: P2 ← Order 101 appears twice!

Why Duplication Matters

Inflated SUM
An order total of \($50\) counted 3 times becomes \($150\) in your revenue report.
Wrong COUNT
COUNT(*) reports 3 orders when there is really only 1. Business decisions built on wrong numbers.
Silent Bug
Queries return no errors. The result looks reasonable but is quietly wrong: the hardest kind of bug to catch.

The Core Rule

1-to-1 1 match → 1 row ✓ Safe Many-to-1 1 match → 1 row ✓ Safe 1-to-Many n matches → n rows ✕ Fan-out! Many-to-Many
\(m \times n\) rows
✕ Explosion! Quick Test:
\(rows\_out > rows\_in\)?
→ Duplication!

Visualizing the Fan-Out

orders id total 1
\($50\)
2
\($30\)
3
\($20\)
True SUM = \($100\)
items id order_id A 1 B 1 C 1 D 2 After JOIN: 4 rows (was 3 orders)
\( \text{SUM(total)} = \$50 + \$50 + \$50 + \$30 = \)\($180\) (should be \($100\)!)

Safe vs. Dangerous Joins

Safe Join Dangerous Join
Relationship Many-to-one One-to-many or many-to-many
Join key uniqueness Unique in right table Not unique in right table
Row count after Same as left table Larger than left table
SUM / COUNT ✓ Correct ✕ Inflated
Example orders → customers orders → order_items

How to Detect Duplication

1
Check row counts. Compare COUNT(*) before and after the join. If rows increased, you have fan-out.
2
Test key uniqueness. Run a GROUP BY on the join key in the right table. If any group has \( \text{COUNT}(*) > 1 \), that key is not unique.
3
Look for repeated primary keys. After the join, GROUP BY the left table's primary key. Any group with \( \text{COUNT}(*) > 1 \) means duplication.
4
Compare aggregates. Compute SUM on the base table alone, then on the joined result. If they differ, duplication is inflating your numbers.

How to Fix Duplication

1
Aggregate before joining. Pre-aggregate the right table into one row per key, then join the summary. This eliminates fan-out entirely.
2
Use DISTINCT. If you only need columns from the left table, wrap the query or use SELECT DISTINCT to remove duplicates after the join.
3
Use a subquery or CTE. Compute your aggregate in a subquery on a single table, avoiding the join altogether for that metric.
4
Use COUNT(DISTINCT ...). If you must join, use COUNT(DISTINCT left_table.id) instead of COUNT(*) to avoid inflated counts.

Example 1: The Broken Query

-- Goal: total revenue per customer SELECT c.name, SUM(o.total) AS revenue FROM customers c JOIN orders o ON c.id = o.cust_id JOIN payments p ON o.id = p.order_id GROUP BY c.name;

Example 1: The Fix

-- Fix: aggregate orders BEFORE joining payments WITH order_totals AS ( SELECT cust_id, SUM(total) AS revenue FROM orders GROUP BY cust_id ) SELECT c.name, ot.revenue FROM customers c JOIN order_totals ot ON c.id = ot.cust_id;

Example 2: COUNT Inflation

-- How many orders does each customer have? SELECT c.name, COUNT(*) AS num_orders FROM customers c JOIN orders o ON c.id = o.cust_id JOIN order_items oi ON o.id = oi.order_id GROUP BY c.name;
namenum_orders (wrong)actual orders
Alice52
Bob31

Example 3: Double One-to-Many

The worst case: joining a table to two one-to-many tables simultaneously. This creates a cross product between the two child tables for each parent row.

-- Joining orders to BOTH items AND payments SELECT o.id, oi.product, p.amount FROM orders o JOIN order_items oi ON o.id = oi.order_id JOIN payments p ON o.id = p.order_id;

Common Mistakes

✕ Trusting COUNT(*)
Using COUNT(*) after a one-to-many join counts duplicated rows, not unique entities. Use COUNT(DISTINCT id) instead.
✕ Joining Then Aggregating
Performing SUM or AVG on a column from the "one" side after a fan-out join inflates the result. Aggregate before joining.
✕ Ignoring Row Counts
Not checking if the joined result has more rows than expected. Always compare row counts before and after to catch fan-out early.

Summary of Strategies

Strategy When to Use SQL Pattern
Pre-aggregate Need SUM/AVG from "one" side CTE with GROUP BY, then JOIN
COUNT(DISTINCT) Counting unique entities COUNT(DISTINCT table.id)
Subquery One metric from one table SELECT ... (SELECT ... FROM ...)
DISTINCT Only need left-table columns SELECT DISTINCT left.*
Row count check Debugging any join Compare COUNT(*) before/after

Question 1 of 5

You join an orders table (100 rows) to an order_items table where each order has an average of 3 items. Approximately how many rows will the result have?

Question 2 of 5

Which of the following is the best way to prevent SUM(order_total) from being inflated by a one-to-many join?

Question 3 of 5

After a join, you notice that COUNT(*) returns 500, but the left table only has 200 rows. What does this indicate?

Question 4 of 5

An order has a total of \($80\). It has \(4\) line items and \(2\) payments. If you join orders to both line_items and payments, how many times will that \($80\) be counted in SUM(total)?

Question 5 of 5

Which SQL function can give you the correct count of unique orders even after a fan-out join?