5.2 EXISTS vs IN, NOT EXISTS vs NOT IN & Derived Tables
Learn when EXISTS beats IN, why NOT EXISTS is dramatically safer than NOT IN around NULLs, why SELECT 1 works inside EXISTS, and how to alias Derived Tables cleanly.
1. How EXISTS Works (Short-Circuit Boolean Check)
EXISTS (subquery) does NOT care about the actual values returned by the inner query — it only asks one yes/no question:
"Does the subquery return AT LEAST ONE row?"
The moment the database finds just 1 matching row, EXISTS immediately returns TRUE and short-circuits (stops scanning the rest of that customer's 10,000 orders!).
-- Find every user who has placed AT LEAST ONE paid order
SELECT u.user_id, u.name
FROM users u
WHERE EXISTS (
SELECT 1
FROM orders o
WHERE o.user_id = u.user_id
AND o.status = 'paid'
);
Why
SELECT 1insideEXISTS?
BecauseEXISTSignores the columns completely —SELECT 1,SELECT *, andSELECT NULLall execute identically!SELECT 1simply signals to other engineers: "I only care whether a row exists."
2. EXISTS vs IN & NOT EXISTS vs NOT IN (Top Interview Table!)
| Comparison | IN / NOT IN | EXISTS / NOT EXISTS |
|---|---|---|
Behavior with NULLs | 🚨 NOT IN BREAKS (returns 0 rows if subquery has even 1 NULL!) | ✅ 100% immune to NULLs! |
| Short-Circuiting | Often materializes the full inner list | Stops at the very first matching row |
| Best When... | Inner list is small (IN ('paid', 'shipped') or small subquery) | Inner table is large and indexed on the join key (orders.user_id) |
| Duplicate Safety | Never duplicates outer rows | Never duplicates outer rows (unlike a 1:Many INNER JOIN!) |
EXISTS vs INNER JOIN — Why EXISTS Prevents Duplicate Rows!
If Aarav has 5 paid orders:
users INNER JOIN ordersreturns Aarav 5 times (forcing you to add an expensiveDISTINCT).users WHERE EXISTS (SELECT 1 FROM orders ...)returns Aarav exactly ONCE — noDISTINCTneeded!
3. Derived Tables (Subqueries Inside FROM)
Sometimes you need an aggregate of an aggregate — like "What is the average of each department's total payroll?"
SQL forbids AVG(SUM(salary)), so you put the first aggregation inside FROM (...) AS alias:
-- Step 1 (inner): Compute total payroll per department
-- Step 2 (outer): Average those department totals!
SELECT ROUND(AVG(dept_payroll), 2) AS avg_department_payroll
FROM (
SELECT department, SUM(salary) AS dept_payroll
FROM employees
GROUP BY department
) AS dept_summary; -- Every derived table MUST have an alias!
Watch Out: Every subquery in
FROM (...)MUST be given an alias (likeAS dept_summary), or PostgreSQL and MySQL will both throw a syntax error!
4. Quick Check Your Understanding
Module 5.2 Quick Quiz
Keep Exploring: Related Lessons & Tools
All Courses →Paste any Python, JS, Java, or C++ snippet to estimate Time & Space complexity, or enter input size N to see which algorithms pass in 1s.
Test regular expressions live with color-coded match highlights, capture group inspection, plain-English token breakdown, find-and-replace, and Python/JS snippets.