Quick revision
The short answer
Customers with at least one order: SELECT c.* FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id). Customers with none: the same query with NOT EXISTS. EXISTS is preferred over JOIN plus DISTINCT because the join returns one row per order and then needs a sort or hash to remove the duplicates, while EXISTS only asks whether a match exists, can stop at the first one, and is planned as a semi-join that returns each customer once.
What to remember
In this answer, we wrote the two queries with EXISTS and NOT EXISTS, saw that a join returns one row per order and needs DISTINCT, which sorts or hashes every joined row, and learned that EXISTS only checks for a match, is planned as a semi-join or anti-join, can stop at the first match, and ignores its select list. We also saw that NOT EXISTS is safe with NULLs where NOT IN is not.
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.
Customers with at least one order: SELECT c.* FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id). Customers with none: the same query with NOT EXISTS. EXISTS is preferred over JOIN plus DISTINCT because the join returns one row per order and then needs a sort or hash to remove the duplicates, while EXISTS only asks whether a match exists, can stop at the first one, and is planned as a semi-join that returns each customer once.
Why this question is asked
Questions like 'which customers have ordered' and 'which have never ordered' come up in almost every application: inactive-user cleanups, marketing segments, data checks. They look easy, and the common answers, a join with DISTINCT and a LEFT JOIN with IS NULL or a NOT IN, work on small data and then fail in subtle ways. Interviewers ask this to see whether we know the semi-join and anti-join forms and can explain why they are both clearer and usually cheaper. In this answer, we will set up a small example, write both queries, compare them with the join version, and look at how the database runs EXISTS.
1A Quick Recap of EXISTS
EXISTS takes a subquery and is true if the subquery returns at least one row, false if it returns none. The subquery is usually correlated, which means it refers to a column of the outer query, here c.id, so it is evaluated for each customer. NOT EXISTS is simply the opposite: true when the subquery returns no rows.
In database terms, 'keep the outer rows that have a match' is called a semi-join, and 'keep the outer rows that have no match' is an anti-join. Neither adds columns from the inner table and neither repeats outer rows. EXISTS and NOT EXISTS are the direct way to write them in SQL.
2Writing Both Queries
Here is a small data set. Ada has three orders, Ben has one, and Cy has none.
Notice that Ada appears once, although she has three orders. EXISTS only asks a yes or no question per customer, so the number of matches does not matter. Notice also the SELECT 1 inside: the select list of an EXISTS subquery is ignored, because only the presence of a row counts. SELECT 1, SELECT * and SELECT o.id all behave the same; SELECT 1 is just a convention that tells the reader no data is used.
3The Join Version and Why It Needs DISTINCT
Many people write the first query as a join. A join pairs each customer with each of their orders, so it returns one row per order, not per customer.
| JOIN + DISTINCT | EXISTS | |
|---|---|---|
| Rows produced by the join | One per order (50 million) | One per customer with an order |
| Extra step | Sort or hash to remove duplicates | None |
| Can stop early per customer | No, reads every order | Yes, at the first match |
| Columns from orders available | Yes | No, only a yes or no |
DISTINCT fixes the result, but it costs work. The database must first produce all the joined rows, one per order, and then remove duplicates with a sort or a hash aggregate over all of them. For a customer table of 1 million rows and an orders table of 50 million, the join produces 50 million rows only to throw away 49 million of them. DISTINCT also compares every selected column, so a wide c.* makes it more expensive, and it can hide real duplicates if the customer table itself had any.
4How the Database Runs EXISTS
Modern planners do not run a correlated EXISTS literally, one subquery per customer. PostgreSQL turns it into a Semi Join node, and NOT EXISTS into an Anti Join node, and then chooses a strategy. With a nested loop and an index on orders(customer_id), it probes the index once per customer and stops at the first matching entry. With a hash semi join, it builds a hash table of the distinct customer ids from orders and checks each customer against it. Either way, each customer is emitted at most once and no duplicate removal is needed afterwards.
So the advantage of EXISTS is partly speed, but mostly that it says exactly what we mean, which lets the planner pick the best way to do it. For the 'never ordered' query, NOT EXISTS is also the safe choice: the alternative NOT IN (SELECT customer_id FROM orders) returns no rows at all if any customer_id is NULL, while NOT EXISTS is unaffected. A LEFT JOIN ... WHERE o.id IS NULL is correct too and is usually planned as the same anti join, but it is easier to get wrong when more conditions are added.
5When a Join Is the Right Choice
The join is not wrong; it answers a different question. If the result needs data from orders, such as the latest order date or the number of orders, we need the join or an aggregate, and then we group by customer instead of using DISTINCT. EXISTS is the right tool when the inner table only filters the outer one.
One practical note: for both forms, an index on orders(customer_id) is what makes the per-customer probe cheap. A foreign key does not create that index automatically in PostgreSQL, so it is worth checking that it exists.
6Follow-up questions
Is EXISTS always faster than JOIN with DISTINCT?
Not always in practice, because a smart planner can sometimes turn the DISTINCT join into a semi-join itself, and for tiny tables the difference is invisible. But EXISTS is never worse in principle, since it asks for less work, and it is correct without relying on DISTINCT. When it matters, we compare both with EXPLAIN ANALYZE on realistic data.
Why is NOT IN dangerous for the second query?
Because of NULLs. id NOT IN (list) means id is different from every value in the list. If the list contains a NULL, the comparison with that NULL is unknown rather than true, so the whole condition is never true, and the query returns nothing. NOT EXISTS checks for the presence of matching rows instead, so NULLs in orders.customer_id simply do not match and cause no harm.
Can I write these queries in JPA?
Yes. JPQL supports EXISTS and NOT EXISTS with correlated subqueries, for example SELECT c FROM Customer c WHERE NOT EXISTS (SELECT 1 FROM Order o WHERE o.customer = c), and Spring Data lets us put that in an @Query. The Criteria API has exists() on a subquery too. Using them keeps the semantics clear and avoids loading orders just to filter customers.
7Conclusion
In this answer, we wrote the two queries with EXISTS and NOT EXISTS, saw that a join returns one row per order and needs DISTINCT, which sorts or hashes every joined row, and learned that EXISTS only checks for a match, is planned as a semi-join or anti-join, can stop at the first match, and ignores its select list. We also saw that NOT EXISTS is safe with NULLs where NOT IN is not.
Open with
For customers with at least one order I would write SELECT c.* FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id), and for customers who never ordered, the same with NOT EXISTS.
Then, if they want more
The SELECT 1 is just a convention; the select list inside EXISTS is ignored, only whether a row exists matters. The reason I prefer EXISTS over a join with DISTINCT is that they ask different questions.
A join pairs each customer with each of their orders, so a customer with three orders comes back three times, and DISTINCT then has to sort or hash all the joined rows to remove the copies. On 50 million orders that is a lot of rows produced only to be thrown away, and DISTINCT also compares every selected column.
EXISTS asks a yes or no question per customer. The planner turns it into a semi-join, and NOT EXISTS into an anti-join, using a hash or a nested loop with an index probe that can stop at the first match, and each customer comes out once.
For the second query I specifically avoid NOT IN, because one NULL customer_id in orders makes it return nothing. I would also check there is an index on orders.customer_id, since a foreign key does not create one in PostgreSQL. If I need order data in the result, like a count, then I would join and group by the customer instead.
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 "Write two queries: customers who placed at least one order, and customers who never...": https://scrivio-interview-library.netlify.app/databases/sql-joins-and-subqueries/5b94e313c6/