Track 0/9 (0%)
Module 06 · CTEs~16 min · 3 worked queries
Common Table Expressions & Recursive Chains
Name intermediate result relations with WITH clauses, stack readable multi-step pipelines, and unroll recursive sequences.
CTEs turn deeply nested subqueries into sequential named reading stages whose data lineage stays explicit from top to bottom.Module 06 · CTEs · Reading Room
Mental Model
- 01.
Each WITH binding computes a temporary relation visible to later CTEs and the main query body.
- 02.
Recursive CTEs pair an anchor base query with UNION ALL plus a self-referencing step bounded by a WHERE guard.
Interactive Module Lab · CTEs
34. Two CTEs building on each other — sqlWITH dept_pay AS (SELECT department_id, SUM(salary) AS payrollFROM usersGROUP BY department_id),big_depts AS (SELECT department_id, payroll FROM dept_pay WHERE payroll > 250000)SELECT d.name, b.payrollFROM big_depts bJOIN departments d ON d.id = b.department_idORDER BY b.payroll DESC;
Execution Stages4 steps
Stage 01 · CTE
2 in → 2 outWITH BIG_DEPTS AS (…)
Materialized 2 rows before the outer query reads from it.
| # | department_id | payroll | state |
|---|---|---|---|
| 1 | 1 | 463,000 | keep |
| 2 | 2 | 281,000 | keep |
Inspect each evaluated clause in 34. Two CTEs building on each other or animate every row moving between stages in Studio.Open 34. Two CTEs building on each other in Studio →