Chaining Multiple CTEs
Building a pipeline of named steps that reference each other.
Why Chain CTEs
Real interview problems rarely fit in one step. Chaining CTEs lets you build a pipeline of named stages, where each stage transforms the output of the previous one. This mirrors how a senior engineer decomposes a hard query into manageable pieces.
Instead of nesting subqueries three levels deep, you write each step once, give it a name, and let later steps reference it.
The Comma-Separated Syntax
To define several CTEs you write WITH once, then separate each named block with a comma. You do not repeat the WITH keyword.
- One
WITHat the top. - A comma between each CTE definition.
- No comma before the final main query.
WITH a AS (
SELECT customer_id FROM orders
),
b AS (
SELECT customer_id FROM a
)
SELECT *
FROM b;All lessons in this course
- Writing Your First CTE
- Chaining Multiple CTEs
- CTE vs Subquery vs Temp Table
- Refactoring Nested Queries Into CTEs