Sub topic 7
EXISTS or IN: when each reads better
This chapter assumes you can write a basic subquery in WHERE and that you know what a correlated subquery is: an inner query that refers to a column of the outer row. It also assumes you know that NULL means a missing value. The examples use customers, orders, order_items, and products.
IN and EXISTS often return the same rows. The choice between them is mostly about which one makes the question easier to read and which one can express the condition at all.
Two ways to ask the same question
Take the question "which customers have placed an order over 500?" Here it is with IN:
SELECT c.customer_id, c.name
FROM customers c
WHERE c.customer_id IN (
SELECT o.customer_id
FROM orders o
WHERE o.total > 500
);And here it is with EXISTS:
SELECT c.customer_id, c.name
FROM customers c
WHERE EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
AND o.total > 500
);Both return each qualifying customer once. The two forms differ in how you think about them:
INbuilds a set of values. The inner query is a list of customer ids, and the outer query asks whether this customer's id is in the list.EXISTSruns a test for each outer row. The inner query is a question about this customer, and it answers yes or no.
Conceptually, IN compares one value to a set. EXISTS asks whether any row satisfies a condition, and that condition can be anything you can write in a WHERE clause.
Same rows, no duplicates
A common worry is that IN with a subquery repeats outer rows when the subquery returns the same value many times. It does not. IN is a membership test, so a customer with twelve large orders still appears once in the first query above. EXISTS behaves the same way, because it stops at the first match.
This is the difference from a join. A join produces one result row per matching pair, so the join version of this question needs DISTINCT (the semi-join chapter covers this). Both IN and EXISTS avoid the problem.
When IN reads better
Use IN when the question is "is this value one of those values?" and the link between the two queries is a single column on each side.
With a literal list, IN is the clearest option:
SELECT order_id, status
FROM orders
WHERE status IN ('shipped', 'delivered');This is shorter than status = 'shipped' OR status = 'delivered'. Short lists of constants are where IN is strongest.
With a subquery, IN reads well when the inner query stands alone and can be understood and run by itself. The subquery SELECT o.customer_id FROM orders o WHERE o.total > 500 makes sense without the outer query. A reader can paste it into a console and see the list. Correlated subqueries cannot be run this way, because they depend on the outer row.
IN is also a good fit when the set comes from a small lookup:
SELECT p.product_id, p.name
FROM products p
WHERE p.category IN (
SELECT category
FROM featured_categories
);Here featured_categories is a one-column table, and the query reads like a sentence.
When EXISTS reads better
EXISTS is the better choice in four situations.
The link is more than one column
Suppose order_items and a promotions table both have product_id and region columns, and you want the items that match a promotion on both. IN has to compare a pair of columns. Some databases accept that with row-value syntax such as (a, b) IN (SELECT x, y ...), but SQL Server does not. EXISTS works everywhere:
SELECT oi.order_id, oi.product_id
FROM order_items oi
WHERE EXISTS (
SELECT 1
FROM promotions pr
WHERE pr.product_id = oi.product_id
AND pr.region = oi.region
);Each correlation condition is a separate line, and adding a third condition means adding one more AND.
The link is not an equality
IN can only test equality. EXISTS can use any comparison. This query finds orders that have a later order from the same customer:
SELECT o.order_id, o.customer_id, o.order_date
FROM orders o
WHERE EXISTS (
SELECT 1
FROM orders o2
WHERE o2.customer_id = o.customer_id
AND o2.order_date > o.order_date
);There is no way to write this with a plain IN, because the condition compares two rows by < or > instead of looking one value up in a list.
The inner query needs several tables
Assume products has a category column. To find customers who bought a book, the IN version nests three levels:
SELECT c.customer_id, c.name
FROM customers c
WHERE c.customer_id IN (
SELECT o.customer_id
FROM orders o
WHERE o.order_id IN (
SELECT oi.order_id
FROM order_items oi
WHERE oi.product_id IN (
SELECT p.product_id
FROM products p
WHERE p.category = 'Books'
)
)
);The EXISTS version joins the inner tables once and correlates at one point:
SELECT c.customer_id, c.name
FROM customers c
WHERE EXISTS (
SELECT 1
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id
WHERE o.customer_id = c.customer_id
AND p.category = 'Books'
);Both are correct. The second keeps the whole relationship in one place, so it is easier to extend with another filter.
The question is about absence
For "has no matching row", NOT EXISTS is the safe form. Its sibling NOT IN has a trap when the subquery can return NULL, which the next chapter covers. The positive forms IN and EXISTS do not have this problem. If the subquery returns a NULL among other values, IN ignores it for matching purposes, because x IN (1, NULL) is true when x is 1 and unknown otherwise, and a WHERE clause treats unknown like false.
Side-by-side comparison
| Situation | IN | EXISTS |
|---|---|---|
| Literal list of values | Best choice | Not applicable |
| One-column link, standalone inner query | Reads naturally | Works, slightly longer |
| Link on two or more columns | Row-value syntax only, not in every database | Works everywhere |
| Link by `<`, `>`, or `<>` | Cannot express it | Works |
| Inner query joins several tables | Nested levels | One subquery with joins |
| Absence ("has none") | Risky because of `NULL` | Safe with `NOT EXISTS` |
| Duplicates in the inner result | Outer rows are not repeated | Outer rows are not repeated |
A decision flow
What about performance?
Beginners often hear "EXISTS is faster than IN" or the reverse. Neither claim holds as a rule. Most modern optimizers, including those in PostgreSQL, SQL Server, Oracle, and recent MySQL versions, recognize both patterns as a semi-join and can produce the same plan for either one. An optimizer can be free to choose between probing the inner table once per outer row and building a hash table of the inner values, and it makes that choice from statistics and indexes rather than from which keyword you wrote.
Older or simpler engines have been known to run an IN subquery as a dependent subquery once per outer row, which can be slow. If a query is slow, do not rewrite it on a hunch. Compare the execution plans of both forms in your database, for example with EXPLAIN. The chapter on execution and indexing covers how to read them.
A practical rule: choose the form that states the question most clearly, and change it only if the plan shows a problem.
Common mistakes
- Selecting more than one column in an
INsubquery.IN (SELECT customer_id, total ...)fails with an error in most databases, because the subquery must return one column to match a single value. If you need to match several columns, switch toEXISTS. - Forgetting the correlation in
EXISTS.EXISTS (SELECT 1 FROM orders o WHERE o.total > 500)has no link to the outer row. It is true for every customer if any order exceeds 500 and false for every customer otherwise. A correlated condition, such aso.customer_id = c.customer_id, is what ties the test to each outer row. - Using
INwhen the inner column can beNULLand you later addNOT. A query that works asINcan silently break when someone edits it intoNOT IN. WritingEXISTSfrom the start avoids this edit hazard. - Treating the two as always interchangeable. They are interchangeable only when the link is a single equality. Anything else needs
EXISTS.
Exercises
Exercise
Rewrite this query with EXISTS, then say whether the result can contain a customer twice. SELECT c.customerid, c.name FROM customers c WHERE c.customerid IN ( SELECT o.customerid FROM orders o WHERE o.orderdate >= DATE '2026-01-01' );
Show answer
The EXISTS version is: SELECT c.customerid, c.name FROM customers c WHERE EXISTS ( SELECT 1 FROM orders o WHERE o.customerid = c.customerid AND o.orderdate >= DATE '2026-01-01' ); No customer appears twice in either version. IN and EXISTS are membership tests on the outer row, so a customer with many matching orders is returned once.
Exercise
A table shipments has columns orderid and productid. Write a query that returns the rows of orderitems that have a matching shipment on both orderid and product_id. Explain why EXISTS suits this better than IN.
Show answer
SELECT oi.orderid, oi.productid FROM orderitems oi WHERE EXISTS ( SELECT 1 FROM shipments s WHERE s.orderid = oi.orderid AND s.productid = oi.product_id ); The link uses two columns. A plain IN can compare only one value to one column of the subquery, and row-value syntax such as (a, b) IN (SELECT ...) is not available in every database. EXISTS handles any number of conditions with AND.
Exercise
Can you write "orders that have a later order from the same customer" with IN? If not, say why and show the EXISTS version.
Show answer
No. IN tests equality between a value and a set, and this question compares two order dates with a greater-than test. The EXISTS version is: SELECT o.orderid FROM orders o WHERE EXISTS ( SELECT 1 FROM orders o2 WHERE o2.customerid = o.customerid AND o2.orderdate > o.order_date );