SQL · Module 05: Subqueries, EXISTS & CTEs (WITH)Tutorial 14 of 24

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.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

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!).

SQL
-- 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 1 inside EXISTS?
Because EXISTS ignores the columns completely — SELECT 1, SELECT *, and SELECT NULL all execute identically! SELECT 1 simply signals to other engineers: "I only care whether a row exists."


2. EXISTS vs IN & NOT EXISTS vs NOT IN (Top Interview Table!)

ComparisonIN / NOT INEXISTS / NOT EXISTS
Behavior with NULLs🚨 NOT IN BREAKS (returns 0 rows if subquery has even 1 NULL!)✅ 100% immune to NULLs!
Short-CircuitingOften materializes the full inner listStops 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 SafetyNever duplicates outer rowsNever 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 orders returns Aarav 5 times (forcing you to add an expensive DISTINCT).
  • users WHERE EXISTS (SELECT 1 FROM orders ...) returns Aarav exactly ONCE — no DISTINCT needed!

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:

SQL
-- 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 (like AS dept_summary), or PostgreSQL and MySQL will both throw a syntax error!


4. Quick Check Your Understanding

Module 5.2 Quick Quiz

Q1.Why do senior engineers almost always prefer NOT EXISTS over NOT IN when checking against another table?
Q2.Why does WHERE EXISTS (SELECT 1 FROM orders o WHERE o.user_id = u.user_id) avoid duplicate users even if a user has 50 orders?

Keep Exploring: Related Lessons & Tools

All Courses →