Quick revision
The short answer
The duplicates come from the join itself: one customer with 40 orders produces 40 joined rows, and DISTINCT then has to sort or hash the whole joined result to collapse them again. If the goal is customers who have orders, WHERE EXISTS is a semi-join that stops at the first matching order and never creates duplicates. If order data is needed, aggregate orders per customer first and join that result.
What to remember
In this answer, we traced the duplicates to a one-to-many join that fans each customer out into one row per order, and saw that DISTINCT makes the database build and then sort or hash all of those rows. EXISTS turns the query into a semi-join that stops at the first matching order, and aggregating orders before joining keeps the join one-to-one when order data is needed. DISTINCT also hides inflated sums, which SUM(DISTINCT) cannot fix, and the same fan-out appears in JPA fetch joins.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The duplicates come from the join itself: one customer with 40 orders produces 40 joined rows, and DISTINCT then has to sort or hash the whole joined result to collapse them again. If the goal is customers who have orders, WHERE EXISTS is a semi-join that stops at the first matching order and never creates duplicates. If order data is needed, aggregate orders per customer first and join that result.
Why this question is asked
Adding DISTINCT to make duplicates go away is one of the most common quick fixes in SQL, and one of the most expensive. It treats the symptom while the cause, a join that multiplies rows, keeps doing its work and sometimes corrupts sums along the way. Interviewers ask this to see whether we understand where duplicates come from and know the semi-join and pre-aggregation patterns. In this answer, we will recap one-to-many joins, see why DISTINCT is slow here, rewrite the query with EXISTS, rewrite it with pre-aggregation when order data is needed, look at the correctness bugs DISTINCT hides, and finish with the same problem in JPA.
1Where the Duplicates Come From
customers to orders is a one-to-many relationship: one customer can have many orders. A join returns one row for every matching pair, so a customer with 40 orders appears 40 times. This is called fan-out: the join fans one row on the left out into many rows. Nothing is wrong with the data; the query simply asked for pairs.
With 200,000 customers and 9 million orders, the join produces 9 million rows, even though the answer has at most 200,000.
2Why SELECT DISTINCT Takes 8 Seconds
DISTINCT does not prevent the duplicates; it removes them afterwards. The database must first build all 9 million joined rows and then compare them, either by sorting them so that equal rows sit next to each other, or by inserting each into a hash table and skipping the ones already there. Both need memory proportional to the data, and when the sort does not fit into the configured working memory, work_mem in PostgreSQL, it spills to temporary files on disk. That is where the 8 seconds go: building 9 million rows only to throw away 8.8 million of them.
| Approach | Rows produced | Extra work |
|---|---|---|
| JOIN + DISTINCT | 9,000,000 | sort or hash 9M rows, may spill to disk |
| WHERE EXISTS (semi-join) | at most 200,000 | one index probe per customer, stops at first match |
| Aggregate orders first, then JOIN | 200,000 groups | one pass over orders, no fan-out |
3Rewrite 1: EXISTS When We Only Need Customers
If the question is which customers have placed orders, we do not need order rows at all. EXISTS asks exactly that.
The database plans this as a semi-join: for each customer it needs to know only whether at least one matching order exists, so it can stop at the first one. With an index on orders(customer_id), that is one short index lookup per customer, or a hash semi-join that builds a set of customer ids once. Either way, it never creates the 9 million rows, and duplicates cannot appear because each customer row is emitted at most once. In practice this kind of rewrite often turns seconds into tens of milliseconds. IN (SELECT customer_id FROM orders) is also a semi-join and is planned the same way in modern PostgreSQL and MySQL.
4Rewrite 2: Aggregate First When We Need Order Data
Often the report also wants something about the orders, such as how many each customer placed. Then we collapse orders to one row per customer before joining, so the join is one-to-one.
The subquery reads orders once and produces at most one row per customer. The join then matches each customer to a single summary row, so no row is multiplied and nothing needs to be deduplicated. If we also want customers with no orders, we change JOIN to LEFT JOIN and wrap the numbers in COALESCE(s.order_count, 0).
5The Bugs That DISTINCT Hides
Fan-out is not only slow, it also breaks aggregates, and DISTINCT on the outer rows does nothing to fix that. Suppose someone extends the original query to report each customer's credit limit total per region.
The first query counts each customer's limit once per order. The tempting fix, SUM(DISTINCT), is wrong in a different way: it sums distinct values, so two different customers with the same limit collapse into one. The only correct fix is to stop the fan-out, using EXISTS to filter or aggregating before joining. When a developer reaches for DISTINCT, it is worth asking why duplicates appeared, because the same cause may be inflating a number elsewhere in the query.
6The Same Problem in JPA
In JPA, a fetch join of a collection, such as SELECT c FROM Customer c JOIN FETCH c.orders, produces the same fan-out in SQL. Older Hibernate versions returned the same Customer object once per order, which is why JPQL queries often carried DISTINCT. Hibernate 6 removes the duplicate entity references from the result automatically, but the SQL still transfers every joined row, and with two collections fetched at once the rows multiply as a product (check your version's behaviour and warnings). Combining a collection fetch join with pagination is worse: Hibernate cannot apply the limit in SQL and paginates in memory, logging a warning about it.
So the same advice applies. To filter entities by the existence of children, use an EXISTS subquery in JPQL or a query that does not fetch the collection. To load children, fetch them in a second query by a batch of parent ids, through @BatchSize, the default_batch_fetch_size setting or an explicit IN query, instead of one large multiplied join.
7Follow-up questions
Is EXISTS always faster than a JOIN with DISTINCT?
Not always, but it is never worse in practice and usually much better when each customer has many orders. When the relationship is almost one-to-one, the difference is small. The bigger benefit is that EXISTS states the intent, which keeps the optimizer and future readers from guessing.
What about NOT EXISTS versus NOT IN?
For customers without orders, prefer NOT EXISTS. NOT IN (SELECT customer_id FROM orders) returns no rows at all if the subquery contains a single NULL, because x NOT IN (..., NULL) is never true. NOT EXISTS has no such trap and is planned as an anti-join.
Is DISTINCT ever the right answer?
Yes, when the duplicates are meaningful to remove and do not come from an unintended join, for example listing the distinct countries customers live in. The warning sign is DISTINCT added after a join to hide repeated parent rows.
8Conclusion
In this answer, we traced the duplicates to a one-to-many join that fans each customer out into one row per order, and saw that DISTINCT makes the database build and then sort or hash all of those rows. EXISTS turns the query into a semi-join that stops at the first matching order, and aggregating orders before joining keeps the join one-to-one when order data is needed. DISTINCT also hides inflated sums, which SUM(DISTINCT) cannot fix, and the same fan-out appears in JPA fetch joins.
Open with
The real problem is not the duplicates, it is the join. Customers to orders is one-to-many, so a customer with 40 orders comes back 40 times. With nine million orders the join produces nine million rows, and DISTINCT then has to sort or hash all of them to throw almost all of them away, often spilling to disk, which is where the 8 seconds go.
Then, if they want more
If the requirement is customers who have ordered, I would rewrite it with WHERE EXISTS, selecting 1 from orders where the customer id matches. That is a semi-join: the database only needs to find the first matching order for each customer, ideally with an index on orders customer_id, and it never creates duplicates, so DISTINCT goes away.
If the report also needs order data, like order counts or totals, I would aggregate orders by customer_id in a subquery first and join that, so the join is one-to-one.
I would also check whether the DISTINCT is hiding a correctness bug, because a sum over the fanned-out rows counts each customer value once per order, and SUM DISTINCT is not a fix since equal amounts from different customers collapse.
In JPA the same happens with fetch joins of collections, so I filter with EXISTS and load children in batches instead.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Hibernate 6
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- PostgreSQL documentation, The SQL Language
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "A query joining customers to orders returned duplicate customers, so a developer added...": https://scrivio-interview-library.netlify.app/databases/sql-fundamentals/258900215e/