# Topic 35: EXISTS & NOT EXISTS
Boolean semi-join checks, short-circuit execution, and why NOT EXISTS is superior to NOT IN.
1. Definition
EXISTS is a boolean operator that tests for the presence of any rows returned by a subquery, returning TRUE as soon as the first matching row is found.
2. Explain Like I'm 5
EXISTS is like peeking into a room to see if anyone is inside. As soon as you spot one person, you say "YES!" and stop looking. You don't need to count all 50 people.
3. Animation & Visual Simulation
Interactive Engine TraceEXISTS & NOT EXISTS Visual Simulator
SELECT u.email FROM users u
WHERE NOT EXISTS (
SELECT 1 FROM logins l WHERE l.user_id = u.id AND l.login_time > NOW() - INTERVAL '30 days'
);Active InputStep 1: Input & Parsing Stage
Initiating EXISTS & NOT EXISTS
Checking Table Invariants
The database engine inspects active tables, verifies permissions, and prepares the physical operation.
4. Real-World Example
Finding all customers who have placed at least one order.
| id | name |
|---|---|
| 1 | Alice (Has orders) |
| 2 | Bob (Has orders) |
| 3 | Charlie (0 orders) |
5. SQL Syntax
ANSI SQL / PostgreSQL DialectSELECT u.id, u.name FROM users u WHERE EXISTS ( SELECT 1 FROM orders o WHERE o.user_id = u.id );
SELECT u.id, u.name FROM users u WHERE NOT EXISTS ( SELECT 1 FROM orders o WHERE o.user_id = u.id );
6. Important Rules & Behaviors
| Rule | Behavioral Explanation |
|---|---|
| Short-Circuit Evaluation | EXISTS terminates scanning as soon as the very first matching row is identified. |
| Projection Irrelevant | Writing SELECT 1, SELECT *, or SELECT NULL inside EXISTS makes no difference; the engine only inspects row existence. |
| Semi-Join Execution | Optimizers convert EXISTS into high-speed Hash Semi-Joins or Index Scans. |
| Semi-join short-circuiting | EXISTS stops scanning the inner table as soon as the first matching tuple is located (best-case O(1)). |
| Projection list irrelevance | The projection list in SELECT inside EXISTS is ignored by the optimizer; SELECT 1 and SELECT * are identical. |
7. Deep Dive: EXISTS vs IN vs JOIN Performance
Historically, EXISTS was faster than IN because it short-circuited. Modern query planners frequently rewrite both into identical Semi-Join execution plans. However, NOT EXISTS remains vastly superior to NOT IN because NOT IN breaks when NULLs are present.
-- Clean, safe, and fast Semi-Join: SELECT c.name FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id AND o.amount > 500);
8. Advantages & Disadvantages
Advantages
- •Short-circuits immediately on the first match.
- •Immune to the Three-Valued Logic NULL bugs that plague NOT IN.
Disadvantages & Trade-offs
- •Writing correlated subqueries for EXISTS can be less readable than simple joins.
9. Common Interview Questions
Q1.Why does "SELECT 1" vs "SELECT *" inside EXISTS make ZERO performance difference?
EXISTS only tests for row existence (cardinality > 0); it never projects or retrieves actual column data. The Cost-Based Optimizer parses the subquery, strips out the projection list entirely, and transforms the operation into an internal boolean semi-join. Writing SELECT 1, SELECT *, or SELECT 'pizza' compiles to the exact same execution plan.
Q2.Why is NOT EXISTS strictly safer and faster than NOT IN when NULLs are present?
Because of Three-Valued Logic! If an inner query returns even one NULL, NOT IN evaluates to UNKNOWN for all rows, returning ZERO results. NOT EXISTS evaluates a boolean existence check: a row either exists or does not. NULL values in the inner table do not cause NOT EXISTS to fail or return UNKNOWN, making it 100% bug-free and allowing the optimizer to use efficient Hash Anti-Joins.
Q3.How does the engine physically execute an EXISTS Semi-Join?
In a Semi-Join, as soon as the engine finds the first matching row in the inner table for a given outer row, it immediately stops scanning the inner table, emits the outer row, and advances to the next outer row. Unlike an INNER JOIN, it never duplicates the outer row even if the inner table has 1,000 matches.
Q4.What is the difference between an Anti-Join and a Semi-Join?
A Semi-Join (EXISTS) returns rows from the outer table that have AT LEAST ONE match in the inner table (without duplicating outer rows). An Anti-Join (NOT EXISTS) returns rows from the outer table that have ZERO matches in the inner table. Both execute in O(N + M) using hash or merge algorithms.
Q5.Can you use EXISTS with an uncorrelated subquery?
Yes! An uncorrelated EXISTS tests whether a global condition holds true: SELECT * FROM orders WHERE EXISTS (SELECT 1 FROM system_flags WHERE maintenance_mode = false); If the subquery returns any row, the condition evaluates to TRUE for all rows; if empty, the query returns zero rows.
10. Interview-Ready Answer
“EXISTS evaluates boolean existence using short-circuit semi-join logic. Unlike NOT IN, which breaks when NULL values are present, NOT EXISTS handles nullable columns deterministically, making it the industry standard for anti-joins.”
11. Quick Test
What does "SELECT 1" inside "WHERE EXISTS (SELECT 1 FROM orders WHERE ...)" signify?