EXISTS vs. IN
SQL Subqueries
Master two essential SQL operators for filtering with subqueries: understand when to use each, how they differ in execution, and which one to reach for in every scenario.
What Are Subqueries?
A subquery is a query nested inside another query. It lets you ask multi-step questions in a single SQL statement: "Show me all customers who have placed at least one order."
The IN Operator
IN checks whether a value matches any value in a list. That list can be hard-coded or produced by a subquery.
The EXISTS Operator
EXISTS checks whether a correlated subquery returns at least one row. It doesn't care about what data comes back: just whether something exists.
How IN Executes
How EXISTS Executes
The Core Rule
Correlated vs. Non-Correlated
EXISTS almost always uses a correlated subquery: the inner query references a column from the outer query. IN typically uses a non-correlated (independent) subquery.
Key Distinction
| IN | EXISTS | |
|---|---|---|
| Returns | A list of values | TRUE or FALSE |
| Subquery type | Non-correlated (usually) | Correlated (typically) |
| NULLs in subquery | Can cause issues | No problem |
| Short-circuits? | No (builds full list) | Yes (stops at first match) |
| Best when inner result | Is small | Is large (with index) |
The NULL Trap with IN
If the subquery for IN returns any NULL values, the result of NOT IN can become unexpected. This is one of the most common SQL bugs.
Performance Considerations
How to Choose
Example 1: Simple IN
Goal: Find all students enrolled in either "Math" or "Science" classes.
Example 2: EXISTS with Correlation
Goal: Find all products that have been ordered at least once in the last 30 days.
Example 3: NOT EXISTS is Safer
Goal: Find customers who have never placed an order. The orders table has some rows where customer_id is NULL.
Common Mistakes
Summary Comparison
| Feature | IN | EXISTS |
|---|---|---|
| Syntax simplicity | Simpler | Requires alias + correlation |
| NULL safety | Risky with NOT IN | Always safe |
| Multi-column checks | Not supported | Supported |
| Hard-coded list | Natural fit | Not applicable |
| Large inner tables | Slower (full materialization) | Faster (short-circuit) |
| Optimizer rewrite | Modern databases often treat them equivalently | |
Question 1 of 5
What does the EXISTS operator return?
Question 2 of 5
You write WHERE id NOT IN (SELECT parent_id FROM items) and the subquery returns {10, 20, NULL}. What happens?
Question 3 of 5
Which SQL operator is typically paired with a correlated subquery?
Question 4 of 5
When is IN generally more appropriate than EXISTS?
Question 5 of 5
Query A:
SELECT name FROM employees WHERE dept_id IN (SELECT id FROM departments WHERE location = 'NYC');
Query B:
SELECT name FROM employees e WHERE EXISTS (SELECT 1 FROM departments d WHERE d.id = e.dept_id AND d.location = 'NYC');
Both queries return the same result. Which statement about them is true?