Reading Room · Module 06
Track 0/9 (0%)
Course completion
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.

Trace Live in StudioAll Modules
Core Relational Rule
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

  1. 01.

    Each WITH binding computes a temporary relation visible to later CTEs and the main query body.

  2. 02.

    Recursive CTEs pair an anchor base query with UNION ALL plus a self-referencing step bounded by a WHERE guard.

Frequent Pitfall to Avoid
Omitting the termination predicate inside a recursive step and relying on engine recursion caps.

Interactive Module Lab · CTEs

34. Two CTEs building on each other — sql
WITH dept_pay AS (
SELECT department_id, SUM(salary) AS payroll
FROM users
GROUP BY department_id
),
big_depts AS (
SELECT department_id, payroll FROM dept_pay WHERE payroll > 250000
)
SELECT d.name, b.payroll
FROM big_depts b
JOIN departments d ON d.id = b.department_id
ORDER BY b.payroll DESC;
Execution Stages4 steps
Stage 01 · CTE

WITH BIG_DEPTS AS (…)

2 in → 2 out

Materialized 2 rows before the outer query reads from it.

#department_idpayrollstate
11463,000keep
22281,000keep
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 →

Worked Presets in This Module

33. Common Table Expression (CTE)

WITH gives a query a name so the main query can read it like a table.

34. Two CTEs building on each other

Later CTEs can read earlier ones, so you can build an answer in readable steps.

35. Recursive CTE: counting to 8

A recursive CTE starts with one row, then keeps adding rows built from the previous ones until the condition stops it.

Navigation

LivePreparation

Client-side workspace · saved locally