MintQueryStart free
← All guides

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

customers
idname
1Ana
2Ben
3Chloe
4Dev
orders
order_idcustomer_id
1011
1021
1031
1042
1053

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;
nameorder_id
Ana101
Ana102
Ana103
Ben104
Chloe105

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.

authors
idname
1Noor
2Sam
3Tess
4Uma
books
book_idauthor_idtitle
11Salt
21Stone
31Smoke
43Tide

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