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.
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.
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.
Why Duplication Matters
The Core Rule
Visualizing the Fan-Out
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
How to Fix Duplication
Example 1: The Broken Query
Example 1: The Fix
Example 2: COUNT Inflation
| name | num_orders (wrong) | actual orders |
|---|---|---|
| Alice | 5 | 2 |
| Bob | 3 | 1 |
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.
Common Mistakes
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?