Mastering MySQL for Data AnalystsLesson 25 of 42
Lesson 25 of 42

Correlated Subqueries: EXISTS & NOT EXISTS in MySQL

Overview & Learning Objectives

While standard subqueries execute once independently of the outer query, a Correlated Subquery references columns from the outer query, executing repeatedly for every candidate row evaluated. The `EXISTS` operator tests whether the correlated subquery returns at least one row, stopping immediately upon finding the first match (short-circuiting). `NOT EXISTS` provides the safest, highest-performance method for identifying missing or inactive records.

  • Write correlated subqueries referencing outer table identifiers.
  • Deploy `EXISTS` and `NOT EXISTS` for existence verification.
  • Understand why `EXISTS` short-circuits execution and outperforms `COUNT(*) > 0`.

Industry Standard

Standard: Analytics engineering standards at Stripe mandate `NOT EXISTS` over `NOT IN` to ensure queries never fail silently when candidate columns contain NULLs.

Real-World Example: ScoopCraft Repeat Customer & Churn Segmentation

ScoopCraft isolates customers who ordered in October 2026 but have zero orders in November 2026 (churned cohort).

Customer IDCustomer NameHas Oct Order (Outer)Has Nov Order? (EXISTS Subquery)Cohort Status
CUST-101Rahul SharmaYESYES (Match found)Retained Active
CUST-102Kavita ReddyYESNO (0 rows in Nov)Churned in Nov (NOT EXISTS Match)
CUST-103Ananya SenYESYES (Match found)Retained Active

Syntax & Core SQL Implementation

-- Correlated subquery: Compare product price to category average
SELECT p1.product_name, p1.category, p1.price
FROM products p1
WHERE p1.price > (
    SELECT AVG(p2.price) 
    FROM products p2 
    WHERE p2.category = p1.category  -- Correlation to outer row
);

-- High-performance EXISTS check (Short-circuits on first match)
SELECT c.customer_id, c.customer_name
FROM customers c
WHERE EXISTS (
    SELECT 1 
    FROM orders o 
    WHERE o.customer_id = c.customer_id 
      AND o.order_total > 500.00
);

-- NOT EXISTS: Safe anti-join (Immune to NULL pitfalls)
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
);

Parameters & Arguments Breakdown

  • EXISTS: Returns TRUE as soon as the inner query returns at least one row, halting further subquery scanning.
  • NOT EXISTS: Returns TRUE if the inner query returns 0 rows.
  • SELECT 1 inside EXISTS: Convention indicating that column projection in EXISTS is completely ignored by the engine.

Sample Walkthrough (Q&A)

Question: Why is "WHERE EXISTS (SELECT 1 FROM orders ...)" faster than "WHERE (SELECT COUNT(*) FROM orders ...) > 0"?

SQL Pattern: EXISTS vs COUNT(*) > 0

Result: EXISTS short-circuits instantly upon finding the 1st match; COUNT(*) must scan and count every single matching row

Explanation: EXISTS stops scanning immediately when 1 record is verified, saving massive CPU and I/O cycles.

Common Mistakes & Limitations

  • Projecting heavy columns like `SELECT *` inside `EXISTS`; while MySQL optimizes this, `SELECT 1` is standard professional convention.
  • Using correlated subqueries in the `SELECT` column list on multi-million row tables without supporting indexes, causing exponential $O(N \times M)$ execution times.

Keyboard Shortcuts (MySQL Workbench)

ActionWindowsMac
Execute QueryCtrl + EnterCmd + Enter

Pro Tips & Modern Best Practices

  • `NOT EXISTS` is completely immune to NULL values in the child table, unlike `NOT IN` which evaluates to empty when NULLs exist.
  • Ensure the inner table has an index on the correlated join column (`o.customer_id`) to allow instant index lookups per outer row.