SQL · Module 05: Subqueries, EXISTS & CTEs (WITH)Tutorial 15 of 24
All Tutorials·~1.5 hrs

5.3 Common Table Expressions (WITH) & Recursive CTEs

Replace unreadable nested subqueries with clean, top-to-bottom CTE pipelines (WITH), compare CTE vs Subquery vs Temporary Table, and traverse org charts & graphs using WITH RECURSIVE.

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

1. Why CTEs (WITH) Changed Modern SQL Forever

Have you ever seen a 60-line SQL query with 4 nested SELECTs inside FROM? Reading it inside-out is painful.
A CTE (Common Table Expression) lets you name each intermediate step cleanly at the top using WITH, turning spaghetti SQL into a clean, top-to-bottom data pipeline!

SQL
-- Clean, self-documenting 2-step CTE pipeline:
WITH paid_totals AS (
    SELECT
        user_id,
        COUNT(*)    AS order_count,
        SUM(amount) AS total_spent
    FROM orders
    WHERE status = 'paid'
    GROUP BY user_id
),
vip_users AS (
    SELECT user_id, order_count, total_spent
    FROM paid_totals
    WHERE total_spent >= 5000
)
SELECT
    u.name,
    u.email,
    v.order_count,
    v.total_spent
FROM vip_users v
INNER JOIN users u ON u.user_id = v.user_id
ORDER BY v.total_spent DESC;

2. CTE vs Subquery vs Temporary Table vs View (Essential Comparison!)

FeatureSubqueryCTE (WITH)Temporary Table (CREATE TEMP TABLE)View (CREATE VIEW)
ReadabilityPoor when nested > 2 levels✅ Best (top-to-bottom steps)Good for multi-query scriptsReusable across users
Reusable in Same Query?❌ Must copy-paste✅ Yes (reference same CTE multiple times!)✅ Yes (for entire session)✅ Yes (permanently saved)
Supports Recursion?❌ No✅ Yes (WITH RECURSIVE)❌ No❌ No
Can Add Indexes?❌ No❌ No✅ Yes! (Huge win for multi-million-row ETL)Only on Materialized Views
Lifespan1 query1 queryCurrent DB connection/sessionPermanent until DROP VIEW

3. Recursive CTEs (WITH RECURSIVE) — Trees, Org Charts & Date Series!

A Recursive CTE has 2 parts joined by UNION ALL:

  1. Anchor Member (Base Case): The starting row(s) (e.g., the CEO with manager_id IS NULL, or n = 1).
  2. Recursive Member: Queries the CTE itself to step one level deeper until no more rows match!

Example 1: Traverse an Entire Company Org Chart (Any Depth!)

SQL
WITH RECURSIVE org_chart AS (
    -- 1. Anchor: Start at the CEO (Level 1)
    SELECT emp_id, name, manager_id, 1 AS depth
    FROM employees
    WHERE manager_id IS NULL

    UNION ALL

    -- 2. Recursive Step: Find everyone who reports to the previous level
    SELECT e.emp_id, e.name, e.manager_id, oc.depth + 1
    FROM employees e
    INNER JOIN org_chart oc ON e.manager_id = oc.emp_id
)
SELECT emp_id, name, depth
FROM org_chart
ORDER BY depth, name;

Example 2: Generate a Series of Numbers 1..5 (Zero Tables Needed!)

SQL
WITH RECURSIVE nums AS (
    SELECT 1 AS n
    UNION ALL
    SELECT n + 1 FROM nums WHERE n < 5
)
SELECT n FROM nums;

Watch a Recursive CTE Expand Level-by-Level

Tracing WITH RECURSIVE Org Chart Traversal
Interactive SQL Execution Tracer · Step 1 of 3 (1. Anchor Query (Depth 1))
1WITH RECURSIVE org AS (
2→ SELECT emp_id, name, 1 AS depth FROM emp WHERE manager_id IS NULL
3 UNION ALL
4 SELECT e.emp_id, e.name, o.depth + 1
5 FROM emp e JOIN org o ON e.manager_id = o.emp_id
6) SELECT * FROM org;
Live Table State · 1. Anchor Query (Depth 1)1 row
emp_idnamedepth
1Priya (CEO)1
What the DB engine just did: Base case finds Priya (manager_id IS NULL) at depth 1.

4. Quick Check Your Understanding

Module 5.3 Quick Quiz

Q1.How long does a CTE (WITH my_cte AS (...)) exist in the database?
Q2.What are the two mandatory parts of a WITH RECURSIVE CTE?

Keep Exploring: Related Lessons & Tools

All Courses →