EXISTS & NOT EXISTS: The Operators That Only Care About One Thing
Most SQL operators want to know a value. EXISTS wants to know something simpler: is there anything
there? That single question — "does at least one row match?" — is enough to filter customers,
validate orders, and find records that are missing from a related table. The tricky part is not
writing EXISTS. It is understanding why NOT IN sometimes returns zero rows when you expected
results, and why NOT EXISTS quietly fixes the problem. This guide walks through how EXISTS actually
executes, the NULL trap that trips up experienced developers, the difference between semi-joins and
anti-joins, and eighteen interview questions that go beyond the textbook definition.
🎯 Key Takeaways
EXISTS returns TRUE if the subquery has any rows
NOT EXISTS is safer than NOT IN when NULLs are possible
Semi-joins stop at the first match — that is why EXISTS can be fast
SELECT 1 and SELECT NULL work the same inside EXISTS
Correlated subqueries run once per outer row — index the join column
18 Interview QuestionsBeginner to AdvancedOracle & SQL ServerUpdated Dec 3, 2026
KW
Kailas Warade
✓ Verified Author
Data Engineer · Oracle Certified · SQL & PL/SQL
Kailas works with SQL, PL/SQL, Python, and PySpark to build data pipelines.
He writes the SQL interview guides at Sankalan Data Tech, focused on
practical, real-world answers.
🏆 Oracle Certified💼 Data Engineer📝 SQL & PL/SQL Guides📍 Pune, India
Every other SQL operator you use is asking about a value. = asks "is this equal
to that?" > asks "is this bigger?" LIKE asks "does this match
the pattern?" EXISTS is different. It does not care about values at all.
EXISTS asks one thing: does the subquery return any rows? That is it. If
the subquery returns one row, five rows, or a million rows, EXISTS returns TRUE. If it
returns nothing, EXISTS returns FALSE. The columns you select inside the subquery are
irrelevant [citation:1][citation:4].
-- These three are identical
WHERE EXISTS (SELECT 1 FROM orders WHERE ...)
WHERE EXISTS (SELECT * FROM orders WHERE ...)
WHERE EXISTS (SELECT NULL FROM orders WHERE ...)
That is why you will see SELECT 1 in production code. It is not faster than
SELECT * — the database does not actually read the columns. It is just a
convention that signals "I am only checking for existence." Some developers prefer
SELECT NULL for the same reason [citation:1].
The place where EXISTS becomes genuinely useful is the correlated subquery. It references
a column from the outer query, which means the subquery runs fresh for each outer row. That
sounds expensive — and it can be — but it expresses something that a join cannot: "give me
customers who have at least one order," without worrying about how many orders each
customer has [citation:5][citation:13].
The Sample Data
The examples use two tables: customers and orders. Note that
customer C005 has no orders, and order 1007 has a NULL customer_id — both are
intentional, because they demonstrate the NULL trap later in this guide.
C005 has no matching rows in orders. That makes it the row NOT EXISTS should
return. The NULL in order 1007 is what makes NOT IN behave strangely later.
EXISTS and NOT EXISTS in Their Simplest Form
The most common use of EXISTS is filtering one table based on the presence of related rows
in another. "Show me customers who have placed at least one order."
SELECT c.customer_id, c.customer_name
FROM customers c
WHERE EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
);
For each customer row, the database runs the subquery: is there any order with this
customer's id? Alice, Bob, Charlie, and Diana get TRUE. Ethan gets FALSE and disappears
from the result. Four rows returned.
NOT EXISTS flips it. "Show me customers who have never placed an order."
SELECT c.customer_id, c.customer_name
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
);
Ethan gets TRUE for NOT EXISTS — there is no matching order. Everyone else gets FALSE.
One row returned: C005, Ethan Supplies.
That is the entire pattern. It is readable, it is clear about intent, and it does not
multiply rows the way a join would if a customer had multiple orders. That last point
matters more than people realize — a JOIN to orders would return
Alice twice because she has two orders. EXISTS returns her once.
The NULL Trap That Breaks NOT IN
This is the thing that catches people. You write NOT IN, the query runs
without error, and it returns zero rows. You check the data manually and the row is
definitely missing from the second table. So why is it not showing up?
The answer is NULL. And once you see it, you will never forget it.
-- This returns ZERO rows, even though Ethan has no orders
SELECT customer_id, customer_name
FROM customers
WHERE customer_id NOT IN (
SELECT customer_id FROM orders
);
Why? The orders table contains a NULL customer_id (order 1007).
SQL evaluates NOT IN (C001, C002, C003, C004, NULL) as a series of
comparisons: customer_id != 'C001' AND customer_id != 'C002' AND ... AND
customer_id != NULL.
That last comparison — customer_id != NULL — evaluates to UNKNOWN, not TRUE.
In SQL's three-valued logic, anything compared to NULL is UNKNOWN. And when one part of an
AND chain is UNKNOWN, the whole expression becomes UNKNOWN. UNKNOWN is not TRUE, so the
row is filtered out. Every row. The query returns nothing [citation:2][citation:7].
NOT EXISTS does not have this problem:
-- This returns Ethan correctly
SELECT c.customer_id, c.customer_name
FROM customers c
WHERE NOT EXISTS (
SELECT 1 FROM orders o
WHERE o.customer_id = c.customer_id
);
NOT EXISTS asks "is there a matching row?" If there is no match — or if the matching row
has a NULL in the join column — the answer is simply "no match." No three-valued logic, no
UNKNOWN, no disappeared results [citation:2].
The practical rule: if the subquery column can be NULL, use NOT EXISTS. If you must use
NOT IN, add WHERE column IS NOT NULL to the subquery. But NOT EXISTS is
almost always the cleaner choice.
What the Optimizer Does — Semi-Joins and Anti-Joins
You write EXISTS. The database does not necessarily run it as a loop of subqueries. Modern
optimizers rewrite EXISTS into something called a semi-join, and NOT
EXISTS into an anti-join [citation:3][citation:5].
A semi-join returns each row from the outer table at most once, as soon as it finds a match
in the inner table. It does not keep looking after the first hit. That is why EXISTS can be
fast even on large tables — the database stops scanning the inner table the moment it finds
one matching row [citation:5][citation:13].
An anti-join is the opposite: it returns outer rows only when no match is found. The
database checks the inner table, finds nothing, and keeps the outer row. If it finds a
match, the outer row is discarded.
-- The plan for NOT EXISTS often looks like this
|--Nested Loops(Left Anti Semi Join)
|--Table Scan(customers)
|--Index Seek(orders, customer_id)
That plan is doing exactly what you asked for, just more efficiently than running the
subquery separately for every row. The optimizer recognized the pattern and chose a
strategy that avoids re-reading the same data [citation:5].
The same transformation applies to IN and NOT IN. MySQL, SQL Server, and Oracle all
convert simple IN and EXISTS subqueries into semi-joins when the conditions are right
[citation:3]. That is why you often cannot tell from the execution plan whether the
original query used IN or EXISTS — they became the same thing.
Performance: When EXISTS Is Fast, When It Is Not
There is no universal answer to "is EXISTS faster than IN?" The honest answer is: it
depends on the data, the indexes, and the optimizer.
Three scenarios worth knowing:
Small outer table, indexed inner table. EXISTS is usually fast. For each
outer row, the database does an index lookup, finds a match quickly, and moves on. Tom Kyte
demonstrated this with a small dept table and a large indexed emp
table — the optimizer chose nested loops semi-join with an index probe, which was efficient
[citation:13].
Large outer table, large inner table. The optimizer may switch to a hash
semi-join or merge semi-join. At that point, the difference between EXISTS and IN usually
disappears — they become the same plan [citation:13].
No index on the join column. This is where EXISTS gets slow. A correlated
subquery with no index on the inner table means a full scan for every outer row. That is
O(n × m) work, and it will hurt. The fix is not to rewrite the query — it is to add the
index [citation:5].
One more thing: nested loop semi-joins can have erratic performance. They are fast when
matches are found quickly, slow when they are not. The same query can behave differently
with slightly different data. Indexes are the remedy [citation:5].
18 Interview Questions and Answers
These are the EXISTS and NOT EXISTS questions that come up most often. Every answer stands
on its own, so you can read them in any order.
/
🔍
No matching questions found
Try a keyword like EXISTS, NULL, or semi-join.
EXISTS checks whether a subquery returns any rows at all. It does not care what
columns you select, how many rows come back, or what values they contain. It only
cares about one thing: is the result set empty or not?
SELECT customer_name
FROM customers c
WHERE EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
);
For each customer, the database asks "does this subquery return at least one row?"
If yes, EXISTS is TRUE and the customer appears in the result. If no, EXISTS is
FALSE and the customer is skipped [citation:1][citation:4].
The SELECT 1 is a convention, not a requirement. SELECT *
and SELECT NULL work exactly the same. The database does not actually
read the column list — it only checks row count [citation:1].
EXISTS returns rows where the subquery finds a match. NOT EXISTS returns rows where
the subquery finds no match. They are opposites.
-- Customers WITH at least one order
WHERE EXISTS (SELECT 1 FROM orders WHERE orders.customer_id = customers.customer_id)
-- Customers WITHOUT any orders
WHERE NOT EXISTS (SELECT 1 FROM orders WHERE orders.customer_id = customers.customer_id)
The practical difference matters most when the subquery column can contain NULL.
NOT IN behaves unexpectedly in that case — it can return zero rows even when you
expect results. NOT EXISTS does not have that problem [citation:2][citation:7].
Use NOT EXISTS whenever the relationship is "find rows with no match." It is
clearer about intent and safer with NULLs.
This is the classic NULL trap. SQL evaluates NOT IN as a chain of AND comparisons,
and any comparison with NULL evaluates to UNKNOWN, not TRUE.
Consider WHERE id NOT IN (1, 2, NULL). SQL expands this to:
WHERE id != 1 AND id != 2 AND id != NULL
The last condition — id != NULL — is UNKNOWN for every row. In SQL's
three-valued logic, UNKNOWN is not TRUE. When one part of an AND chain is UNKNOWN,
the whole expression becomes UNKNOWN. The row is filtered out .
If the subquery returns even a single NULL, NOT IN returns zero rows. It does not
matter how many valid values are in the list — the NULL poisons the entire
condition [citation:2][citation:7].
The fix is NOT EXISTS:
WHERE NOT EXISTS (
SELECT 1 FROM orders WHERE orders.customer_id = customers.customer_id
)
NOT EXISTS checks for the presence of a matching row. No NULL comparison, no
UNKNOWN, no disappeared results.
A correlated subquery is one that references a column from the outer query. The
subquery cannot run on its own — it needs a value from the current outer row.
SELECT c.customer_name
FROM customers c
WHERE EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id -- c.customer_id comes from outer query
);
The o.customer_id = c.customer_id is the correlation. For each row in
customers, the database plugs in that row's customer_id
and runs the subquery to see if any orders match [citation:5].
Correlated subqueries can be expensive because they run once per outer row. The
optimizer often rewrites them into semi-joins to avoid that, but if it cannot —
usually because the correlation is complex or the tables are large without indexes —
the query will be slow.
The fix is an index on the inner join column. orders(customer_id) in
this example.
Not always. The honest answer is: it depends. Modern optimizers often rewrite IN
and EXISTS into the same execution plan — a semi-join — which means the
performance difference disappears [citation:3].
When there is a difference:
IN with a small, static list — the database evaluates the list
once and compares. Fast.
EXISTS with an indexed inner table — the database stops at the
first match. Fast.
IN with a large subquery — the database might materialize the
whole result before comparing. Can be slower than EXISTS.
The practical advice: write the query that is clearest about intent. EXISTS is
usually better for "does a match exist?" IN is better for "is this value in a
list?" Check the execution plan if performance matters — do not assume either is
always faster.
A semi-join is an execution strategy where the database returns each row from the
outer table at most once, stopping as soon as it finds a match in the inner table.
-- You write this:
SELECT * FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id);
-- The optimizer may run this (conceptually):
-- For each customer, scan orders until one match is found.
-- If found, return the customer once. Move on.
That "stop at first match" behavior is what makes semi-joins efficient for EXISTS.
The database does not need to count matches or read all matching rows — it only
needs to know that at least one exists [citation:5][citation:13].
Semi-joins are not something you write. They are something the optimizer chooses.
You write EXISTS or IN, and the optimizer decides whether to use a nested loops
semi-join, a hash semi-join, or a merge semi-join.
An anti-join is the opposite of a semi-join. It returns rows from the outer table
that have no match in the inner table.
NOT EXISTS and (safe) NOT IN are transformed into anti-joins:
-- Plan for NOT EXISTS
|--Nested Loops(Left Anti Semi Join)
|--Table Scan(customers)
|--Index Seek(orders, customer_id)
The database checks the inner table for a match. If it finds one, the outer row is
discarded. If it finds nothing, the outer row is kept [citation:5].
The name "anti" comes from the fact that it is the complement of a semi-join. A
semi-join keeps rows with matches. An anti-join keeps rows without matches.
Yes. EXISTS works in the WHERE clause of UPDATE and DELETE just like it does in
SELECT.
-- Mark customers as active only if they have at least one order
UPDATE customers c
SET status = 'Active'
WHERE EXISTS (
SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id
);
-- Delete customers who have never placed an order
DELETE FROM customers c
WHERE NOT EXISTS (
SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id
);
The same semi-join and anti-join transformations apply. The optimizer sees the
EXISTS pattern and rewrites it the same way it would for a SELECT [citation:3].
One caution with DELETE: always run the SELECT version first to verify which rows
will be affected. NOT EXISTS is safe from the NULL trap, but a missing WHERE clause
or a typo in the correlation can still delete more than you intended.
A JOIN returns columns from both tables and can produce duplicate rows. EXISTS
returns each outer row at most once and only tests for a match.
-- JOIN: Alice appears twice because she has two orders
SELECT c.customer_name, o.order_id
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id;
-- EXISTS: Alice appears once, no order details
SELECT c.customer_name
FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id);
Use JOIN when you need data from both tables. Use EXISTS when you only need to
filter the outer table based on a condition in another table [citation:13].
The row multiplication is the practical issue. If Alice has two orders, a JOIN to
orders returns her twice. If you then aggregate — say, count customers — you get
wrong numbers. EXISTS avoids that entirely.
Yes. EXISTS (SELECT NULL FROM ...) is perfectly valid and returns TRUE
if the subquery returns any rows.
-- All of these behave identically
WHERE EXISTS (SELECT 1 FROM orders)
WHERE EXISTS (SELECT * FROM orders)
WHERE EXISTS (SELECT NULL FROM orders)
EXISTS only checks row count. It does not evaluate the selected expressions. A
NULL in the select list is not compared to anything, so there is no three-valued
logic problem [citation:1].
Most developers write SELECT 1 by convention. It reads as "I only care
that a row exists." Some prefer SELECT NULL to make the same point.
Either is fine — the database treats them the same.
EXISTS is powerful, but it is not a universal tool. Its limitations:
It cannot return data from the subquery. Only TRUE or FALSE. If you need the actual values, you need a JOIN.
It cannot be used in the SELECT list. It belongs in WHERE or HAVING, not in the column list.
Correlated EXISTS can be slow without indexes. The subquery runs once per outer row. Without an index on the inner join column, that is a full scan per row.
It does not tell you how many matches exist. Only that at least one does. If you need counts, use a JOIN with GROUP BY or a scalar subquery.
The trade-off is usually worth it. EXISTS is clearer about intent than a JOIN with
DISTINCT, and safer than NOT IN with NULLs.
Both work. Both return rows from the outer table that have no match in the inner
table. The choice is mostly about readability.
-- NOT EXISTS: clear intent
SELECT c.customer_name
FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id);
-- LEFT JOIN with IS NULL: works, but requires recognizing the pattern
SELECT c.customer_name
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id
WHERE o.customer_id IS NULL;
NOT EXISTS reads as "customers with no orders." The LEFT JOIN version reads as
"join customers to orders and keep the rows where the order side is empty." Both
are correct, but the first says what it means [citation:13].
Performance is usually identical because the optimizer rewrites both into
anti-joins. If you find a case where one is faster, the difference is usually
indexes, not the syntax.
Nothing special. EXISTS does not care how many columns the subquery returns. It
only checks whether any rows come back.
-- This is valid
WHERE EXISTS (SELECT customer_id, order_id, amount FROM orders WHERE ...)
-- This is also valid, and does the same thing
WHERE EXISTS (SELECT 1 FROM orders WHERE ...)
That is different from IN, which requires the subquery to return exactly one
column. EXISTS has no such restriction [citation:1].
The convention is to select a constant — 1 or NULL —
because it makes the intent clear. But selecting the actual columns is harmless.
Yes, but the optimizer handles OR conditions differently than AND conditions. With
AND, multiple EXISTS subqueries are combined as a sequence of semi-joins. With OR,
the optimizer has to ensure a row qualifies if either condition is true — which
often means a more complex plan [citation:8].
-- AND: straightforward to optimize
WHERE EXISTS (SELECT 1 FROM orders WHERE ...)
AND EXISTS (SELECT 1 FROM payments WHERE ...)
-- OR: requires more work
WHERE EXISTS (SELECT 1 FROM orders WHERE ...)
OR EXISTS (SELECT 1 FROM payments WHERE ...)
The OR version is still valid SQL. It just may not get the same clean semi-join
plan. If performance matters and the query uses OR with multiple EXISTS clauses,
check the execution plan.
= ANY is the same as IN. It compares a value to each
value in the subquery result and returns TRUE if any comparison matches. EXISTS
only checks for row presence and does not compare values.
-- These are equivalent
WHERE customer_id = ANY (SELECT customer_id FROM orders)
WHERE customer_id IN (SELECT customer_id FROM orders)
-- This is different
WHERE EXISTS (SELECT 1 FROM orders WHERE orders.customer_id = customers.customer_id)
In practice, the optimizer often treats EXISTS and IN (and = ANY) the same when
they express the same logic. The semi-join transformation applies to both
[citation:3].
The distinction matters for NULL behavior. = ANY with a NULL in the
subquery follows the same three-valued logic as IN. EXISTS does not.
Three things to check, in order.
First: is the correlation condition correct? NOT EXISTS
(WHERE orders.customer_id = customers.customer_id) is different from
NOT EXISTS (WHERE orders.customer_id = customers.some_other_column).
A typo in the correlation column silently returns wrong results — no error, just
missing rows.
Second: are there NULLs in the correlation column? If the inner
column can be NULL, the comparison returns UNKNOWN for those rows. They are not
treated as matches, which is usually correct for NOT EXISTS — but if you expected
them to match, that is the bug.
Third: run the EXISTS version first. Change NOT EXISTS to EXISTS
and see which rows do match. The complement of that set is what NOT EXISTS
should return. If the numbers do not add up, the correlation is wrong.
Yes, but the aggregate goes inside the subquery, not outside it.
-- Valid: aggregate inside the subquery
WHERE EXISTS (
SELECT 1
FROM orders
GROUP BY customer_id
HAVING COUNT(*) >= 3
HAVING orders.customer_id = customers.customer_id
)
The subquery returns rows only for customers with three or more orders. EXISTS then
checks whether any such row exists for the current customer.
You cannot write WHERE EXISTS (COUNT(*) > 3) or similar — EXISTS
expects a subquery, not a boolean expression. Aggregates belong inside the
subquery's SELECT or HAVING clause.
NOT EXISTS. It is safe with NULLs, clear about intent, and the optimizer handles
it well.
SELECT c.customer_id, c.customer_name
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
);
The alternatives and why they are worse:
NOT IN — returns zero rows if the subquery has any NULL. The most common bug in this pattern [citation:2].
LEFT JOIN with IS NULL — works, but reads as a join pattern rather than a "no match" query. Less clear.
NOT EXISTS — reads as "no matching order exists," which is exactly what you mean.
Index the inner join column — orders(customer_id) — and the query will
be fast even on large tables. The anti-join transformation means the database does
not run the subquery separately for every row [citation:5].
Mistakes I Keep Seeing
These come up repeatedly in code reviews and interviews. None are exotic, and all are easy
to avoid once you know they exist.
Mistake one: using NOT IN with a nullable column. The query runs, returns
zero rows, and the developer spends an hour checking the data before realizing the subquery
has a NULL. Use NOT EXISTS. Always.
Mistake two: writing EXISTS when a JOIN would be clearer. EXISTS is for
filtering, not for pulling data. If you need columns from the inner table, use a JOIN.
Mistake three: assuming EXISTS is always faster than IN. Modern optimizers
often produce the same plan. Check the execution plan before optimizing based on syntax.
Mistake four: forgetting the index on the inner join column. A correlated
EXISTS subquery without an index on the correlation column is a full scan per outer row.
That will hurt.
Mistake five: using SELECT * inside EXISTS thinking it matters. It does
not. EXISTS only checks row count. SELECT 1, SELECT NULL, and SELECT * are identical.
Follow-Up Questions Interviewers Ask
Getting the first answer right is only half the interview. What decides the outcome is
what happens next. Here is what to prepare for.
After "What is EXISTS?" — expect
"What is the difference between EXISTS and IN?"
"What does SELECT 1 mean inside EXISTS?"
"Can EXISTS be used with UPDATE?"
"What is a correlated subquery?"
After "NOT EXISTS vs NOT IN" — expect
"Why does NOT IN return no rows when the subquery has NULL?"
"What is three-valued logic?"
"How would you fix a NOT IN query that is returning zero rows?"
"Is NOT EXISTS always faster than NOT IN?"
After "semi-joins" — expect
"What is the difference between a semi-join and a regular join?"
"Why does a semi-join stop at the first match?"
"How do you see the semi-join in an execution plan?"
"What is an anti-join?"
For every question above, prepare a second-level answer. The candidates who pass are the
ones who keep going for another thirty seconds and say something useful about why it
matters.
Quick Quiz
Three questions to check whether the topics above have landed.
1. Why does NOT IN return zero rows when the subquery contains NULL?
2. What does a semi-join do differently from a regular join?
3. What is the safest way to find customers with no orders?