Quick revision
The short answer
Before approving, I check that the result is still the same: DISTINCT can hide duplicates that were valid, and changing the select list or adding columns from the joined table changes what DISTINCT compares. Then I compare EXPLAIN ANALYZE plans and timings for both versions on realistic data and parameters, because the join produces one row per match and DISTINCT then sorts or hash-aggregates all of them, which on a 40 million row table is often slower than the semi-join EXISTS already got. I also check the indexes on the correlation columns for both forms, and ask for a benchmark result rather than a general claim.
What to remember
In this answer, we reviewed a rewrite of EXISTS into JOIN plus DISTINCT. We checked semantics first, since DISTINCT can hide valid duplicates and changes meaning when the select list changes, then compared EXPLAIN ANALYZE plans on 40 million rows, where the join produced millions of pairs and a DISTINCT that spilled to disk. We checked indexes on the correlation columns for both forms, and asked for a benchmark so the decision rests on measurements rather than a rule of thumb.
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.
Before approving, I check that the result is still the same: DISTINCT can hide duplicates that were valid, and changing the select list or adding columns from the joined table changes what DISTINCT compares. Then I compare EXPLAIN ANALYZE plans and timings for both versions on realistic data and parameters, because the join produces one row per match and DISTINCT then sorts or hash-aggregates all of them, which on a 40 million row table is often slower than the semi-join EXISTS already got. I also check the indexes on the correlation columns for both forms, and ask for a benchmark result rather than a general claim.
Why this question is asked
Performance changes in code review are tricky, because they come with a reason that sounds technical and is hard to argue with in the moment: 'joins are faster'. Approving them without checking can make the query both slower and subtly wrong. Interviewers use this scenario to see what a careful reviewer looks for: semantics first, then evidence, and a respectful way to ask for it. In this answer, we will look at the change, check whether it keeps the same meaning, compare how both versions run on a 40 million row table, look at indexes, and finish with how to handle the review conversation.
1The Change Under Review
Here is the kind of change in the pull request. The original selects customers who placed an order in the last 30 days. The new version joins orders and removes the duplicates with DISTINCT.
Both look reasonable, and on a small development database both return the same rows in a millisecond. That is exactly why the review needs to go beyond reading the SQL.
2Check 1: Is the Result Still the Same?
EXISTS returns each customer once. The join returns one row per recent order, and DISTINCT collapses rows that are equal in every selected column. These are the same only under assumptions worth checking. If the customers table can contain rows that are genuinely identical in the selected columns, for example two rows with the same id from a bad import or a view without a key, EXISTS keeps both and DISTINCT silently merges them. More often, the select list changes over time: if someone later adds o.created_at to the join version to show the latest order, DISTINCT now compares that column too, and each customer appears once per distinct order date.
There are smaller semantic points too. If the Java code maps the result into a paginated list, ordering and LIMIT now apply after DISTINCT, so the query needs an ORDER BY that includes the DISTINCT columns. And if the code is generated through JPA, a DISTINCT in JPQL can behave differently from SQL DISTINCT for entity queries. So the first question in the review is: what guarantees that every customer appears exactly once, and will it still hold when the query changes?
3Check 2: Compare the Plans on Realistic Data
Next we need evidence about speed. With 40 million rows in orders, the two versions do different work. EXISTS becomes a semi-join: for each customer it needs to find one recent order, and with an index it stops at the first. The join produces one row for every recent order, say 3 million rows for the last 30 days, and then DISTINCT has to sort or hash all 3 million to reduce them to the 800,000 distinct customers.
| EXISTS | JOIN + DISTINCT | |
|---|---|---|
| Rows from the join step | 800,000 customers, each once | 3,000,000 customer-order pairs |
| Extra step | None | Sort or HashAggregate over 3M rows |
| Memory risk | Hash of recent customer ids | Groups of all selected columns; may spill |
| Semantics | Each customer once, always | Depends on the select list staying the same |
| Measured (example) | 1.9 s | 4.3 s |
In this example, the join version is more than twice as slow, and its HashAggregate spilled to disk because it had to hold 800,000 groups of three wide columns. The numbers will differ for other data, and sometimes a planner can turn the DISTINCT join back into a semi-join, so the plans could even be identical. That is exactly why we compare plans and timings, with realistic data volumes and with the parameter values used in production, including a cold cache run, rather than reasoning in general terms.
4Check 3: Indexes for Both Forms
Both versions depend on the index that serves the correlation between customers and orders. For EXISTS with a time condition, an index on orders(customer_id, created_at) lets each per-customer probe find a recent order in a few page reads; an index on orders(created_at, customer_id) lets a hash semi-join read only the last 30 days and get the customer ids from the index alone, as in the plan above. The join version benefits from the same indexes, so if the original EXISTS query was slow, the likely cause is a missing or wrong index, which the rewrite does not fix.
So I would also ask what problem the change is solving. If there was a slow query report, the plan from that report tells us whether the issue was the form of the query or something else: a missing index, stale statistics or a huge time window. Fixing that root cause may make both forms fast.
5Check 4: Ask for the Benchmark
The respectful way to handle a performance change is to ask for the evidence that motivated it. A short comment works well: 'Thanks for looking at this query. Could you add the EXPLAIN ANALYZE output for both versions on the staging data set, and the timing with production-like parameters? Also, the join can return a customer more than once and relies on DISTINCT; can we confirm that holds if the select list changes?' This turns a disagreement about rules of thumb into a comparison of numbers.
If the benchmark shows the join is genuinely faster on our data, we approve it, with a comment in the code explaining why, and perhaps a test that checks each customer appears once. If it shows EXISTS is faster or equal, we keep EXISTS, which is also the clearer expression of the question. Either way the team learns something, and the next review of this kind is quicker.
- Same result in all cases?YesContinue to the plansNoRequest changes: semantics differ
- Plans and timings for both on realistic dataEXPLAIN ANALYZE, real parameters
- Indexes checked for both formscorrelation columns
- Is the new version measurably faster?YesApprove with a comment and a testNoKeep EXISTS
4 steps in order. Play them, or step through them one at a time.
6Follow-up questions
Can a planner turn JOIN plus DISTINCT into a semi-join by itself?
Sometimes. If the planner can prove that the DISTINCT only removes duplicates created by the join, for example when the select list contains only columns of the outer table including its primary key, some optimizers can use a semi-join or remove the duplicates more cheaply. It is not guaranteed and differs between engines and versions, which is another reason to look at the actual plan rather than assume.
What if the developer needs a column from orders in the result?
Then EXISTS cannot provide it, and the question changes: which order's value do we want? If it is the latest order date, a GROUP BY with MAX, or a LATERAL subquery with LIMIT 1, expresses that precisely. DISTINCT over a column from orders is almost never the right answer, because it returns one row per distinct value rather than one per customer.
How do you avoid this discussion repeating in every review?
Write the team's guidance down once, with an example: use EXISTS for existence checks, joins when columns from the other table are needed, and show EXPLAIN ANALYZE for any change justified by performance. Linking to that guidance in a review keeps the conversation short and impersonal.
7Conclusion
In this answer, we reviewed a rewrite of EXISTS into JOIN plus DISTINCT. We checked semantics first, since DISTINCT can hide valid duplicates and changes meaning when the select list changes, then compared EXPLAIN ANALYZE plans on 40 million rows, where the join produced millions of pairs and a DISTINCT that spilled to disk. We checked indexes on the correlation columns for both forms, and asked for a benchmark so the decision rests on measurements rather than a rule of thumb.
Open with
Before approving I would check two things: that it means the same thing, and that it is actually faster. On semantics, EXISTS returns each customer once by definition.
Then, if they want more
The join returns one row per matching order and relies on DISTINCT to collapse them, which only works while the select list contains just customer columns. If someone later adds a column from orders, customers start appearing several times, and DISTINCT can also merge rows that were genuinely different, or fail outright on a json column in PostgreSQL.
On performance, I would ask for EXPLAIN ANALYZE of both versions on realistic data with production parameters. On a 40 million row table, the join might produce three million customer-order pairs, and the DISTINCT then has to sort or hash all of them, possibly spilling to disk, while EXISTS is a semi-join that needs one match per customer.
In my experience the join is often slower, though sometimes the planner makes them equal, which is exactly why I want the numbers. I would also check the indexes, for example orders on customer_id and created_at, because if the original was slow, a missing index is the more likely cause and the rewrite does not fix it.
I would phrase it as a request: thanks, could you add both plans and timings, and confirm the uniqueness holds. If the join is measurably faster, I approve with a comment and a test that each customer appears once; otherwise we keep EXISTS.
About this answer
- Last updated
- 12 November 2026
- 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 "In a code review, a developer replaces EXISTS with a JOIN plus DISTINCT for...": https://scrivio-interview-library.netlify.app/databases/sql-joins-and-subqueries/95e6e769c5/