A CTE, or common table expression, is a named temporary result that you define with the WITH keyword at the top of a query and then use like a table in the query that follows. It exists only while that one query runs. CTEs do not make SQL do anything new; they make long queries readable by letting you build the answer in named steps instead of nesting subqueries three levels deep.
There is one thing a CTE can do that a plain subquery cannot: call itself. That is a recursive CTE, and it is how you walk an org chart or generate a list of dates. Both kinds are covered below with worked examples.
CTE syntax
A CTE has a name, an optional column list, and a query in brackets. The main query comes straight after.
| Part | What it does | Syntax | Example |
|---|---|---|---|
| Single CTE | Names one intermediate result | WITH name AS (query) SELECT … FROM name | WITH big_orders AS (SELECT * FROM orders WHERE amount > 2000) SELECT * FROM big_orders |
| Column list | Renames the CTE’s columns | WITH name (col1, col2) AS (query) | WITH totals (customer_id, spend) AS (SELECT customer_id, SUM(amount) FROM orders GROUP BY customer_id) |
| Several CTEs | Chains steps, separated by commas | WITH a AS (query), b AS (query using a) SELECT … | WITH t AS (…), top_t AS (SELECT * FROM t WHERE spend > 3000) SELECT * FROM top_t |
| Recursive CTE | A CTE that refers to itself | WITH RECURSIVE name AS (anchor UNION ALL recursive part) | WITH RECURSIVE days AS (SELECT … UNION ALL SELECT … FROM days WHERE …) |
The WITH keyword appears once, however many CTEs you define. A second WITH in the middle of the list is the most common syntax error beginners hit.
The data used throughout
The examples use six October orders from a Bengaluru D2C coffee brand. Amounts are in rupees. Note that there are no orders on 2 October; that gap matters for the recursive example.
| order_id | customer_id | order_date | amount |
|---|---|---|---|
| 5001 | C1 | 2026-10-01 | 1499 |
| 5002 | C2 | 2026-10-01 | 899 |
| 5003 | C1 | 2026-10-03 | 2199 |
| 5004 | C3 | 2026-10-03 | 649 |
| 5005 | C2 | 2026-10-04 | 1299 |
| 5006 | C4 | 2026-10-04 | 3499 |
Example 1: customers who spend above average
The question: which customers spent more than the average customer this month? It needs two steps. First total each customer’s spend, then compare each total against the average of those totals.
The query, one clause per row:
| Step | SQL |
|---|---|
| Define the CTE | WITH customer_totals AS ( |
| Its query | SELECT customer_id, COUNT(*) AS orders, SUM(amount) AS total_spend FROM orders GROUP BY customer_id ) |
| Main query | SELECT customer_id, orders, total_spend FROM customer_totals |
| Filter | WHERE total_spend > (SELECT AVG(total_spend) FROM customer_totals) |
The CTE produces four rows: C1 at 3,698, C2 at 2,198, C3 at 649 and C4 at 3,499. Their average is 2,511, so the result is:
| customer_id | orders | total_spend |
|---|---|---|
| C1 | 2 | 3698 |
| C4 | 1 | 3499 |
Notice that customer_totals is used twice, once in FROM and once inside the filter. Written with subqueries instead, the GROUP BY would appear twice, and anyone changing the logic later would have to remember to change both copies. That is the practical case for a CTE: one definition, used as often as you need.
Example 2: chaining CTEs to segment customers
The question: how much revenue came from repeat customers versus one-time buyers? Three steps: count each customer’s orders, label each customer, then total by label. Each step is its own CTE and reads top to bottom.
| Step | SQL |
|---|---|
| CTE 1 | WITH customer_orders AS (SELECT customer_id, COUNT(*) AS n, SUM(amount) AS spend FROM orders GROUP BY customer_id), |
| CTE 2 | segmented AS (SELECT customer_id, spend, CASE WHEN n > 1 THEN ‘Repeat’ ELSE ‘One-time’ END AS segment FROM customer_orders) |
| Main query | SELECT segment, COUNT(*) AS customers, SUM(spend) AS revenue FROM segmented GROUP BY segment |
| segment | customers | revenue |
|---|---|---|
| One-time | 2 | 4148 |
| Repeat | 2 | 5896 |
Half the customers are repeat buyers and they bring in 59% of revenue. The value of the chained form shows up when the question changes. If the business decides “repeat” means three or more orders, you change one number in CTE 2 and nothing else.
Each CTE can read any CTE defined before it, but not one defined after. Order them the way you would explain the logic to a colleague.
Example 3: a recursive CTE to fill missing dates
Group the orders by date and you get three rows, for 1, 3 and 4 October. 2 October is missing because nothing happened, and a chart built on that result draws a straight line across the gap as though sales continued. The fix is to generate every date in the range and LEFT JOIN the orders onto it.
A recursive CTE has two parts joined by UNION ALL: an anchor that runs once, and a recursive part that refers to the CTE itself and runs until it returns no rows.
| Part | SQL (MySQL) |
|---|---|
| Anchor | WITH RECURSIVE days AS (SELECT DATE(‘2026-10-01’) AS d |
| Join the parts | UNION ALL |
| Recursive part | SELECT d + INTERVAL 1 DAY FROM days WHERE d < ‘2026-10-04’) |
| Main query | SELECT days.d, COUNT(o.order_id) AS orders, COALESCE(SUM(o.amount), 0) AS revenue |
| Join | FROM days LEFT JOIN orders o ON o.order_date = days.d GROUP BY days.d ORDER BY days.d |
| d | orders | revenue |
|---|---|---|
| 2026-10-01 | 2 | 2398 |
| 2026-10-02 | 0 | 0 |
| 2026-10-03 | 2 | 2848 |
| 2026-10-04 | 2 | 4798 |
The anchor produces 1 October. The recursive part adds one day to the last row it produced, and stops when the WHERE condition fails at 4 October. COUNT(o.order_id) rather than COUNT(*) matters here: COUNT(*) would count the empty 2 October row as one order.
The other classic recursive case is a hierarchy. Given an employees table where each row holds a manager_id, the anchor selects the person with no manager, and the recursive part joins employees onto the CTE where manager_id matches the previous level’s emp_id, adding 1 to a level counter each time. The result lists everyone with their depth in the org chart, however many levels it has, which no fixed number of self-joins can do.
Where MySQL, PostgreSQL and SQL Server differ
CTEs are standard SQL, but recursion and date arithmetic are where the dialects split.
| Point | MySQL | PostgreSQL | SQL Server |
|---|---|---|---|
| CTE support | From 8.0; none in 5.7 | Yes | Yes |
| Recursive keyword | WITH RECURSIVE (required) | WITH RECURSIVE (required) | Plain WITH; RECURSIVE is a syntax error |
| Add one day in the recursive part | d + INTERVAL 1 DAY | d + 1 (on a DATE) | DATEADD(day, 1, d) |
| Default recursion limit | 1000 levels (cte_max_recursion_depth) | No limit; a missing stop condition runs until cancelled | 100 levels; raise it with OPTION (MAXRECURSION n) at the end of the query |
| Statement before WITH | No rule | No rule | Must end with a semicolon, which is why you see ;WITH in SQL Server code |
The SQL Server limit of 100 catches people generating a year of dates: the query fails at day 101. Add OPTION (MAXRECURSION 400) after the final ORDER BY, or 0 for no limit if you are sure the stop condition is right. In PostgreSQL, the simpler way to make a date list is the built-in generate_series function, and most analysts use that instead of a recursive CTE.
CTE vs subquery vs temp table vs view
All four hold an intermediate result. They differ in how long it lives and who can see it.
| CTE | Subquery | Temporary table | View | |
|---|---|---|---|---|
| Lives for | One query | One query | The session | Until dropped |
| Can be referenced more than once | Yes | No, repeat it | Yes | Yes |
| Can be recursive | Yes | No | No | Only if its query is a recursive CTE |
| Stores data | No | No | Yes | No (unless materialised) |
| Best for | Readable multi-step logic | A short one-off filter | Reusing a heavy result across several queries | Logic other people and reports reuse |
On performance, a CTE is usually neither faster nor slower than the equivalent subquery, because the optimiser treats them much the same. PostgreSQL before version 12 was the exception: it always computed a CTE separately, which could be slow. From version 12 it inlines simple CTEs, and you can force either behaviour with AS MATERIALIZED or AS NOT MATERIALIZED. If you will run the same heavy intermediate result in five different queries, a temporary table beats a CTE, because the CTE is recomputed each time.
Mistakes people make with CTEs
Writing WITH twice. Separate CTEs with commas under one WITH.
Using a CTE after its query has ended. A CTE is gone as soon as the statement finishes. Running the main SELECT on its own, without the WITH block above it, fails because the name no longer exists.
Forgetting the stop condition in a recursive CTE. Without the WHERE in the recursive part, the query runs until it hits the recursion limit, or, in PostgreSQL, until you cancel it.
Using UNION instead of UNION ALL in recursion. UNION removes duplicates at every step, which costs time and can silently drop rows you needed. Use UNION ALL unless you specifically need de-duplication.
Assuming a CTE is cached. In most databases, referencing a CTE twice may compute it twice. It is a readability tool first.
CTEs pair naturally with window functions, since filtering on a rank needs one, and with joins, which our SQL joins guide covers with the same kind of examples. Interviewers ask about CTEs in the intermediate rounds of our SQL interview questions.
Frequently asked questions
What is a CTE in SQL?
A CTE, or common table expression, is a named temporary result set defined with the WITH clause at the start of a query. The query that follows can select from it as if it were a table. It exists only for the duration of that single statement and is mainly used to break complex logic into readable, named steps.
What is the difference between a CTE and a subquery?
Both produce an intermediate result inside one query. A CTE is defined once at the top with a name and can be referenced several times, while a subquery is written inline and must be repeated wherever it is needed. CTEs can also be recursive, which subqueries cannot. Performance is usually the same.
What is a recursive CTE?
A recursive CTE is one that refers to itself. It has an anchor query that runs once and a recursive query that runs repeatedly on the previous step’s output, joined by UNION ALL, until the recursive part returns no rows. It is used for hierarchies such as org charts and category trees, and for generating sequences such as a list of dates.
Is a CTE faster than a subquery?
Usually neither is faster, because most optimisers treat them the same way. PostgreSQL before version 12 materialised every CTE, which could make it slower; version 12 and later inline simple CTEs. If the same heavy result is needed across several separate queries, a temporary table is faster than repeating a CTE.
Does MySQL support CTE?
Yes, from MySQL 8.0, including recursive CTEs written with WITH RECURSIVE. MySQL 5.7 and earlier do not support the WITH clause at all, so on those versions you need subqueries or temporary tables instead.
Can I use a CTE in UPDATE or DELETE?
Yes, in most databases. SQL Server and PostgreSQL allow a CTE in front of UPDATE, DELETE and INSERT, and SQL Server even lets you delete directly from a CTE, which is a common way to remove duplicate rows. MySQL 8.0 also accepts WITH before UPDATE and DELETE. The CTE still lasts only for that one statement.
Write multi-step SQL that others can read
CTEs are what make a 60-line analysis query something a colleague can review. Getting fluent with them takes practice on real, messy data, ideally with someone who points out where your logic breaks.
SkilloVilla’s SQL: Beginner to Advanced course goes from the fundamental statements through aggregation, joins and advanced SQL statements, taught in live classes with mentor support and practice on SQL playgrounds. For SQL inside a full analytics programme with Python and placement support, see the Data Analytics with Python track.