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.
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!
-- 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!)
| Feature | Subquery | CTE (WITH) | Temporary Table (CREATE TEMP TABLE) | View (CREATE VIEW) |
|---|---|---|---|---|
| Readability | Poor when nested > 2 levels | ✅ Best (top-to-bottom steps) | Good for multi-query scripts | Reusable 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 |
| Lifespan | 1 query | 1 query | Current DB connection/session | Permanent until DROP VIEW |
3. Recursive CTEs (WITH RECURSIVE) — Trees, Org Charts & Date Series!
A Recursive CTE has 2 parts joined by UNION ALL:
- Anchor Member (Base Case): The starting row(s) (e.g., the CEO with
manager_id IS NULL, orn = 1). - 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!)
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!)
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
| emp_id | name | depth |
|---|---|---|
| 1 | Priya (CEO) | 1 |
4. Quick Check Your Understanding
Module 5.3 Quick Quiz
Keep Exploring: Related Lessons & Tools
All Courses →Compare two versions of text, source code, config files, or JSON payloads side-by-side using exact LCS diffing with recursive JSON key sorting and patch export.
Paste LeetCode-style level-order tree arrays, graph edge lists, or 2D matrices to render clean vector SVG diagrams and DFS traversals.