Introduction to Common Table Expressions (WITH Clause)
Name intermediate result sets with WITH for clearer analytical queries.
In plain words
A CTE lets you give a name to a mini-query and then use that name later in the same query.
Think of it like…
Showing your working in a maths exam: instead of one giant formula, you write "step 1 = …, step 2 = …, answer = …". Each named step is a CTE.
Where you’ve seen it
A monthly revenue report: one CTE filters paid orders, a second totals them per month, and the final SELECT computes month-over-month growth. Each step can be run and checked on its own while debugging.
Words you’ll hear
- WITH clause
- Defines one or more CTEs before the main statement.
- Scope
- A CTE exists only inside the statement that defines it.
- Chained CTEs
- Later CTEs can refer to earlier ones in the same WITH.
- Materialization
- Whether the database computes a CTE once and stores it, or inlines it into the main query.
Visual diagram
Theory & example queries
Writing and chaining CTEs
Start with WITH, give the CTE a name, and put its query in parentheses. Separate several CTEs with commas; each one can use the CTEs defined before it. The statement then ends with the main SELECT (or INSERT, UPDATE, DELETE) that uses them.
A CTE is a step inside one statement, not a saved object. It disappears when the statement finishes, unlike a view (saved in the schema) or a temporary table (lasts for the session).
| id | customer_id | status | amount | coupon_code |
|---|---|---|---|---|
| 101 | 1 | paid | 249 | NULL |
| 102 | 2 | paid | 120 | WELCOME10 |
| 103 | 1 | shipped | 89.5 | NULL |
WITH paid AS ( SELECT * FROM orders WHERE status = 'paid' ), monthly AS ( SELECT date_trunc('month', created_at) AS MONTH, SUM(amount) AS revenue FROM paid GROUP BY 1 )SELECT MONTH, revenueFROM monthlyORDER BY MONTH;PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
Representative monthly revenue3 sample rows
| month | revenue |
|---|---|
| 2026-09-01 | 18420 |
| 2026-10-01 | 23175 |
| 2026-11-01 | 19640 |
Note: Illustrative totals from paid orders; actual month boundaries, currency units and rows depend on the source data and database date functions.
Key takeaway: Comma-separated, top to bottom, each step can use the ones above it.
Do CTEs make queries faster?
Usually not by themselves; they're mainly for readability. Since PostgreSQL 12, a non-recursive CTE that's referenced once is inlined into the main query and optimised as if you'd written a subquery. Before version 12, PostgreSQL always computed CTEs separately, which could block index use (an "optimization fence").
You can control this with WITH x AS MATERIALIZED (…) to compute it once (useful when it's referenced several times and is expensive) or AS NOT MATERIALIZED to force inlining. MySQL supports CTEs from version 8.0, SQL Server and Oracle have long supported them.
| id | customer_id | status | amount | coupon_code |
|---|---|---|---|---|
| 101 | 1 | paid | 249 | NULL |
| 102 | 2 | paid | 120 | WELCOME10 |
| 103 | 1 | shipped | 89.5 | NULL |
WITH bigAS MATERIALIZED (SELECT customer_id, SUM(amount)AS totalFROM ordersGROUP BY 1)SELECT …FROM big aJOIN big b ON …;PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
Representative materialization behavior
Note: This teaching snippet deliberately uses ellipses and is not executable as written, so concrete result rows cannot be derived. EXPLAIN can confirm whether PostgreSQL materializes the CTE once.
Key takeaway: CTEs are for clarity; check the plan before assuming they change speed.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Break the problem into steps
Write the answer as a list of stages: filter the rows, aggregate them, then compare or rank.
filter → aggregate → compare
When to use it & trade-offs
What it is
A Common Table Expression (CTE) is a named, temporary result set defined with WITH name AS (…) at the start of a query. The main query, and any later CTE in the same WITH, can then use it like a table. It exists only for that one statement.
Why it matters: CTEs turn a deeply nested query into readable, named steps, which makes complex analytics easier to write, review and debug. They're also the only way to write recursive queries in SQL, and interviewers expect you to structure multi-step answers with them.
When to reach for it
- Analytics queries with several stages
- Replacing deeply nested subqueries
- Recursive queries (org charts, category trees) with WITH RECURSIVE
When to avoid or be careful
- Assuming a CTE is cached and shared between statements; it isn't
- Huge chains of CTEs that should really be a view or a data model
- Expecting a CTE alone to make a slow query fast
CTE vs subquery vs view vs temp table
Strengths: Readable named steps that can be reused within the statement.
Watch out: Exists only for that statement.
Strengths: Compact.
Watch out: Nested subqueries quickly become hard to read.
Strengths: Shared or indexed.
Watch out: Extra objects to create, maintain and clean up.
Interview signals & numbers to know
When this topic comes up
- “Make this query more readable”
- “CTE vs subquery”
- Multi-step analytics problems
- WITH clause
- Recursive query
Benchmarks & rules of thumb
- 1 statement
- the lifetime of a CTE
- PostgreSQL 12
- CTEs inlined by default from this version
- MySQL 8.0
- first MySQL version with CTEs
Common mistakes & follow-ups
Common interview mistakes
- Trying to use a CTE in a second, separate statement.
- Giving CTEs meaningless names like t1, t2, t3, which defeats the readability benefit.
- Claiming CTEs are always materialized, or always faster, without checking the database version and plan.
Likely interviewer follow-ups
- What is the difference between a CTE and a temporary table?
- Does using a CTE improve performance? When could it make things worse?
- How would you write a recursive CTE to list every employee under a manager?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Introduction to Common Table Expressions (WITH Clause) with hands-on SQL practice and interview Q&A.