Why does my JOIN return duplicate rows?
Your JOIN returns duplicate rows because a join gives you one row for every matching pair. A customer with three orders matches three times, so the customer appears three times. Most of the time the rows are not real duplicates. Each one is a different match, and you are only looking at the columns that repeat.
How it usually happens
You need a list of customers who have ordered, to send them a thank-you email. Customers are in one table and orders in another, so you join them and select the name. The list comes back longer than the customer table, with Ana in it three times. If that list goes out as it is, Ana gets three emails.
The tables
| id | name |
|---|---|
| 1 | Ana |
| 2 | Ben |
| 3 | Chloe |
| 4 | Dev |
| order_id | customer_id |
|---|---|
| 101 | 1 |
| 102 | 1 |
| 103 | 1 |
| 104 | 2 |
| 105 | 3 |
Ana has three orders. Dev has none.
The query with the repeated names
SELECT c.name
FROM customers c
JOIN orders o ON o.customer_id = c.id
ORDER BY c.name;
| name |
|---|
| Ana |
| Ana |
| Ana |
| Ben |
| Chloe |
Why they are not really duplicates
Add the order id to the same query and the rows stop looking the same.
SELECT c.name, o.order_id
FROM customers c
JOIN orders o ON o.customer_id = c.id
ORDER BY c.name, o.order_id;
| name | order_id |
|---|---|
| Ana | 101 |
| Ana | 102 |
| Ana | 103 |
| Ben | 104 |
| Chloe | 105 |
The join returned one row per order, which is its job. The question was about customers, so the query has to say that.
The fix
Ask whether an order exists, instead of joining to every order.
SELECT c.name
FROM customers c
WHERE EXISTS (
SELECT 1 FROM orders o
WHERE o.customer_id = c.id
)
ORDER BY c.name;
| name |
|---|
| Ana |
| Ben |
| Chloe |
Two other fixes, depending on what you need. SELECT DISTINCT c.name on the original join gives the same list, and it is fine for a quick check. If you want something from the orders too, like how many each customer placed, use GROUP BY and you get one row per customer with a count.
Rule to remember: a join returns one row per match. Before you write it, decide what one row of your result should be: a customer, or an order.
Try it yourself
Same trap, different tables. A small publisher wants to invite its published authors to a dinner.
| id | name |
|---|---|
| 1 | Noor |
| 2 | Sam |
| 3 | Tess |
| 4 | Uma |
| book_id | author_id | title |
|---|---|---|
| 1 | 1 | Salt |
| 2 | 1 | Stone |
| 3 | 1 | Smoke |
| 4 | 3 | Tide |
The query below is meant to list each author who has published at least one book, once, as name, sorted by name. Noor comes back three times. Fix it.
Hint
You only need to know whether a book exists for the author, not which books.
Show solution
SELECT a.name
FROM authors a
WHERE EXISTS (
SELECT 1 FROM books b
WHERE b.author_id = a.id
)
ORDER BY a.name;| name |
|---|
| Noor |
| Tess |
MintQuery has 500+ exercises like this one, in lessons of a few minutes.
Start freeGet the app