SQL CTE: using the WITH clause to write queries in steps
The WITH clause lets you give an intermediate result a name and then query it like a table. A tangled nested query turns into a short list of steps you can check one by one: total each order, add the totals up per customer, then average them per segment.
In short: WITH name AS (SELECT …) SELECT … FROM name. The query in brackets is a CTE (common table expression). It only exists for the single statement that follows it. Separate several CTEs with commas: WITH a AS (…), b AS (…) SELECT …
What you should know first: grouping with GROUP BY, combining tables with JOIN and queries inside queries with subqueries.
Try it now
The order_items table has several rows per order, so before you can filter on what an order is worth, you have to add its lines up. That first step is what goes into the CTE.
Task Large orders worth more than 1000 get a thank-you card. Use WITH to build a helper table order_totals with order_id and total (the sum of quantity * unit_price per order, from order_items). From it, show order_id and total for every order with a total above 1000.
order_items 38 rows, 4 columns
| order_id | product_id | quantity | unit_price |
|---|---|---|---|
| 1001 | 1 | 40 | 4.79 |
| 1001 | 3 | 25 | 2.79 |
| 1001 | 6 | 4 | 24.9 |
| 1002 | 2 | 2 | 3.49 |
| 1002 | 10 | 3 | 5.49 |
| 1003 | 1 | 60 | 4.69 |
| 1003 | 11 | 6 | 84.9 |
| 1003 | 3 | 50 | 2.59 |
| 1004 | 4 | 3 | 179 |
| 1004 | 9 | 3 | 269 |
| 1005 | 5 | 1 | 449 |
| 1006 | 1 | 30 | 4.79 |
| 1006 | 7 | 10 | 6.99 |
| 1007 | 8 | 2 | 219 |
| 1007 | 11 | 4 | 89.9 |
| 1007 | 1 | 20 | 4.99 |
| 1008 | 4 | 6 | 175 |
| 1008 | 2 | 5 | 3.49 |
| 1009 | 10 | 120 | 4.99 |
| 1009 | 2 | 40 | 3.19 |
| 1009 | 9 | 2 | 279 |
| 1010 | 7 | 2 | 6.99 |
| 1010 | 2 | 1 | 3.49 |
| 1011 | 12 | 1 | 129 |
| 1011 | 1 | 10 | 4.99 |
| 1011 | 3 | 12 | 2.79 |
| 1012 | 6 | 8 | 23.9 |
| 1012 | 1 | 40 | 4.69 |
| 1013 | 9 | 1 | 279 |
| 1014 | 5 | 2 | 439 |
| 1014 | 4 | 2 | 179 |
| 1015 | 1 | 50 | 4.79 |
| 1015 | 11 | 2 | 89.9 |
| 1016 | 10 | 4 | 5.49 |
| 1017 | 2 | 3 | 3.49 |
| 1017 | 7 | 2 | 6.99 |
| 1018 | 1 | 80 | 4.79 |
| 1018 | 6 | 10 | 24.9 |
How the WITH clause works
A CTE has three parts: the keyword WITH, a name followed by AS, and a query in brackets. Straight after it comes the main query, which uses the name as if it were a table. The warehouse wants to know which products sell the most units:
WITH units AS (
SELECT product_id, SUM(quantity) AS units_sold
FROM order_items
GROUP BY product_id
)
SELECT p.name, u.units_sold
FROM units u
JOIN products p ON p.product_id = u.product_id
ORDER BY u.units_sold DESC
LIMIT 5;
| name | units_sold |
|---|---|
| Copy paper, 500 sheets | 330 |
| Notebook A5, ruled | 127 |
| Lever arch file, gray | 87 |
| Blue ballpoint pens, 10-pack | 51 |
| Black ink cartridge | 22 |
Read it top to bottom: first units is built with one row per product, then the main query adds the product name and sorts. Nothing gets saved. Once the statement ends, units is gone and the next query has never heard of it.
Three habits make CTEs easier. Name every calculated column inside the CTE with AS, or you can't refer to it later. Pick a name that says what the step holds, such as units, order_totals or customer_revenue. And run the query inside the brackets on its own first, before you wrap WITH around it.
A CTE instead of a nested subquery
Which categories have an average price above the average of all categories? With subqueries the same grouping appears twice, once nested two levels deep:
SELECT category, avg_price
FROM (SELECT category, AVG(price) AS avg_price
FROM products GROUP BY category)
WHERE avg_price > (SELECT AVG(avg_price)
FROM (SELECT category, AVG(price) AS avg_price
FROM products GROUP BY category));
With a CTE you write the grouping once and use it twice:
WITH category_prices AS (
SELECT category, AVG(price) AS avg_price
FROM products
GROUP BY category
)
SELECT category, ROUND(avg_price, 2) AS avg_price
FROM category_prices
WHERE avg_price > (SELECT AVG(avg_price) FROM category_prices);
| category | avg_price |
|---|---|
| Electronics | 209 |
| Furniture | 319 |
The six category averages come to about 99.78 overall, and only Electronics and Furniture beat it. If the rule changes later, say only products in stock should count, you edit one place instead of two.
Task Sales wants to know which orders are above the average order value. Order value means the sum of quantity * unit_price per order, from order_items. Show order_id and total for those orders. Use a CTE so you only write the calculation once.
order_items 38 rows, 4 columns
| order_id | product_id | quantity | unit_price |
|---|---|---|---|
| 1001 | 1 | 40 | 4.79 |
| 1001 | 3 | 25 | 2.79 |
| 1001 | 6 | 4 | 24.9 |
| 1002 | 2 | 2 | 3.49 |
| 1002 | 10 | 3 | 5.49 |
| 1003 | 1 | 60 | 4.69 |
| 1003 | 11 | 6 | 84.9 |
| 1003 | 3 | 50 | 2.59 |
| 1004 | 4 | 3 | 179 |
| 1004 | 9 | 3 | 269 |
| 1005 | 5 | 1 | 449 |
| 1006 | 1 | 30 | 4.79 |
| 1006 | 7 | 10 | 6.99 |
| 1007 | 8 | 2 | 219 |
| 1007 | 11 | 4 | 89.9 |
| 1007 | 1 | 20 | 4.99 |
| 1008 | 4 | 6 | 175 |
| 1008 | 2 | 5 | 3.49 |
| 1009 | 10 | 120 | 4.99 |
| 1009 | 2 | 40 | 3.19 |
| 1009 | 9 | 2 | 279 |
| 1010 | 7 | 2 | 6.99 |
| 1010 | 2 | 1 | 3.49 |
| 1011 | 12 | 1 | 129 |
| 1011 | 1 | 10 | 4.99 |
| 1011 | 3 | 12 | 2.79 |
| 1012 | 6 | 8 | 23.9 |
| 1012 | 1 | 40 | 4.69 |
| 1013 | 9 | 1 | 279 |
| 1014 | 5 | 2 | 439 |
| 1014 | 4 | 2 | 179 |
| 1015 | 1 | 50 | 4.79 |
| 1015 | 11 | 2 | 89.9 |
| 1016 | 10 | 4 | 5.49 |
| 1017 | 2 | 3 | 3.49 |
| 1017 | 7 | 2 | 6.99 |
| 1018 | 1 | 80 | 4.79 |
| 1018 | 6 | 10 | 24.9 |
This exercise is part of Premium.
Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.
See Premium Already Premium? Log in
The first exercise in this lesson is free.
Chaining several CTEs
For a query with several steps, write WITH once and put commas between the CTEs. Each one can use the ones defined before it. Which low-stock products (fewer than 20 on hand) are selling, and how many?
WITH units AS (
SELECT product_id, SUM(quantity) AS units_sold
FROM order_items
GROUP BY product_id
),
low_stock AS (
SELECT product_id, name, stock
FROM products
WHERE stock < 20
)
SELECT l.name, l.stock, u.units_sold
FROM low_stock l
JOIN units u ON u.product_id = l.product_id
ORDER BY u.units_sold DESC;
| name | stock | units_sold |
|---|---|---|
| Yellow sticky notes, 12 pads | 0 | 14 |
| Comfort office chair | 12 | 11 |
| 27-inch monitor | 15 | 6 |
| Standing desk | 5 | 3 |
| Mono laser printer L30 | 8 | 2 |
| Cross-cut shredder | 0 | 1 |
The sticky notes are out of stock and still the best seller among the low-stock items, which is worth a call to the supplier. In the next exercise the second CTE builds directly on the first. You need that whenever you calculate on top of sums, such as the average of customer revenue: the database rejects AVG(SUM(…)), so the totals per customer need a step of their own.
Task Management asks: how much revenue does a customer bring in on average, split by customer segment? Cancelled orders don't count, and only customers with revenue count. Show segment, customers (the number of those customers in the segment) and avg_revenue (average revenue per customer, rounded to two decimal places), highest average first. Build it in steps with two CTEs: order_totals per order first, then customer_revenue per customer.
order_items 38 rows, 4 columns
| order_id | product_id | quantity | unit_price |
|---|---|---|---|
| 1001 | 1 | 40 | 4.79 |
| 1001 | 3 | 25 | 2.79 |
| 1001 | 6 | 4 | 24.9 |
| 1002 | 2 | 2 | 3.49 |
| 1002 | 10 | 3 | 5.49 |
| 1003 | 1 | 60 | 4.69 |
| 1003 | 11 | 6 | 84.9 |
| 1003 | 3 | 50 | 2.59 |
| 1004 | 4 | 3 | 179 |
| 1004 | 9 | 3 | 269 |
| 1005 | 5 | 1 | 449 |
| 1006 | 1 | 30 | 4.79 |
| 1006 | 7 | 10 | 6.99 |
| 1007 | 8 | 2 | 219 |
| 1007 | 11 | 4 | 89.9 |
| 1007 | 1 | 20 | 4.99 |
| 1008 | 4 | 6 | 175 |
| 1008 | 2 | 5 | 3.49 |
| 1009 | 10 | 120 | 4.99 |
| 1009 | 2 | 40 | 3.19 |
| 1009 | 9 | 2 | 279 |
| 1010 | 7 | 2 | 6.99 |
| 1010 | 2 | 1 | 3.49 |
| 1011 | 12 | 1 | 129 |
| 1011 | 1 | 10 | 4.99 |
| 1011 | 3 | 12 | 2.79 |
| 1012 | 6 | 8 | 23.9 |
| 1012 | 1 | 40 | 4.69 |
| 1013 | 9 | 1 | 279 |
| 1014 | 5 | 2 | 439 |
| 1014 | 4 | 2 | 179 |
| 1015 | 1 | 50 | 4.79 |
| 1015 | 11 | 2 | 89.9 |
| 1016 | 10 | 4 | 5.49 |
| 1017 | 2 | 3 | 3.49 |
| 1017 | 7 | 2 | 6.99 |
| 1018 | 1 | 80 | 4.79 |
| 1018 | 6 | 10 | 24.9 |
orders 18 rows, 5 columns
| order_id | customer_id | order_date | status | employee_id |
|---|---|---|---|---|
| 1001 | 1 | 2026-01-08 | delivered | 3 |
| 1002 | 4 | 2026-01-12 | delivered | 4 |
| 1003 | 3 | 2026-01-20 | delivered | 3 |
| 1004 | 7 | 2026-02-03 | delivered | 4 |
| 1005 | 2 | 2026-02-11 | cancelled | 8 |
| 1006 | 1 | 2026-02-25 | delivered | 3 |
| 1007 | 10 | 2026-03-04 | delivered | 2 |
| 1008 | 5 | 2026-03-17 | delivered | 4 |
| 1009 | 8 | 2026-03-30 | delivered | 3 |
| 1010 | 6 | 2026-04-07 | delivered | 8 |
| 1011 | 12 | 2026-04-22 | delivered | 4 |
| 1012 | 3 | 2026-05-06 | delivered | 3 |
| 1013 | 9 | 2026-05-19 | cancelled | 8 |
| 1014 | 7 | 2026-06-02 | shipped | 4 |
| 1015 | 1 | 2026-06-10 | shipped | 3 |
| 1016 | 11 | 2026-06-12 | open | NULL |
| 1017 | 4 | 2026-06-13 | open | NULL |
| 1018 | 10 | 2026-06-14 | open | NULL |
customers 12 rows, 7 columns
| customer_id | name | city | country | customer_since | segment | phone |
|---|---|---|---|---|---|---|
| 1 | Harbor Fremont Partners | Boston | USA | 2021-03-15 | Business | 617-555-0142 |
| 2 | Emily Carter | Chicago | USA | 2022-07-01 | Consumer | NULL |
| 3 | Riverside County Office | Riverside | USA | 2020-11-20 | Government | 951-555-0110 |
| 4 | Raj Patel | Leeds | UK | 2023-01-09 | Consumer | 0113 496 0123 |
| 5 | Lakeview Hotel Ltd | Manchester | UK | 2022-04-18 | Business | 0161 496 0456 |
| 6 | Olivia Brooks | Austin | USA | 2024-02-27 | Consumer | NULL |
| 7 | Greene & Shaw LLP | London | UK | 2021-09-05 | Business | 020 7946 0321 |
| 8 | Maple Grove High School | Austin | USA | 2023-08-14 | School | 512-555-0187 |
| 9 | Chloe Evans | Boston | USA | 2025-05-30 | Consumer | 617-555-0199 |
| 10 | Northline Printing Co | Toronto | Canada | 2020-06-12 | Business | 416-555-0133 |
| 11 | Daniel Kim | Seattle | USA | 2024-10-03 | Consumer | NULL |
| 12 | Westbrook Dental Clinic | Chicago | USA | 2022-12-01 | Business | 312-555-0164 |
This exercise is part of Premium.
Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.
See Premium Already Premium? Log in
The first exercise in this lesson is free.
A look ahead: recursive CTEs
With WITH RECURSIVE a CTE may read its own output. That is how you walk a hierarchy such as the reporting lines in the employees table: an anchor query picks the person at the top, and a second query after UNION ALL keeps adding everyone whose manager_id was found in the previous round. In our company that gives three levels: Karen Mitchell, then Tom Bradley, Nina Cooper and Sarah Long, then six more people. It isn't part of these exercises.
Common mistakes
Writing WITH twice
WITH a AS (…) WITH b AS (…) SELECT … is invalid; the second WITH has to be a comma. The exercise reports a syntax error near "WITH". The correct form is WITH a AS (…), b AS (…) SELECT …
A semicolon after the CTE
The CTE and the query that follows are one statement. A semicolon after the closing bracket ends it too early, and the exercise tells you the query stops in the middle and asks about a missing quote or bracket. When you see that message, look for a semicolon after the CTE first.
An average straight in WHERE
WHERE total > AVG(total) looks natural but doesn't work: WHERE checks one row at a time and doesn't know the average of all rows yet. The exercise says functions like SUM don't belong in WHERE and points to HAVING, but HAVING won't get you there either. Fetch the average with a small subquery on the CTE instead: WHERE total > (SELECT AVG(total) FROM order_totals).
A sum inside a sum
The database rejects AVG(SUM(quantity * unit_price)) in a single query, and the exercise shows the same message as for the average in WHERE. Two levels of calculation need two steps: the sums in a CTE first, then the average on top.
A calculated column without a name
If the CTE only says SUM(quantity * unit_price) without AS total, the column is named after the formula. The main query can't find total, and the exercise reports that there is no column "total".
A typo in the CTE name
Call the CTE order_totals and then write FROM order_total, and the database goes looking for a real table with that name. The exercise says the table doesn't exist and lists the tables that do. Your CTE isn't on that list, because it was never stored as a table.
WITH in MySQL, PostgreSQL, SQL Server and SQLite
The basic form WITH name AS (…), name2 AS (…) SELECT … is the same in all four. MySQL supports it from version 8.0 and SQLite from 3.8.3 (February 2014). The differences are in recursion and the details:
| Database | Recursion | Worth knowing |
|---|---|---|
| MySQL | WITH RECURSIVE, required as soon as one CTE is recursive | repeating WITH for the second CTE is explicitly not allowed |
| PostgreSQL | WITH RECURSIVE | a CTE used once is folded into the main query, one used several times is computed once; you can override this with MATERIALIZED or NOT MATERIALIZED; INSERT, UPDATE and DELETE are allowed inside WITH |
| SQL Server | no RECURSIVE keyword; default limit of 100 levels, change it with OPTION (MAXRECURSION …) | the statement before a CTE must end with a semicolon; ORDER BY inside a CTE only together with TOP or OFFSET |
| SQLite (these exercises) | WITH RECURSIVE | MATERIALIZED and NOT MATERIALIZED since version 3.35.0 |
The SQL Server rule matters in everyday scripts: if a statement without a semicolon sits above WITH …, you get an error, so always close the previous statement with a semicolon. Microsoft also points out that a CTE's result isn't stored; every reference runs its query again.
Sources: MySQL Reference Manual (What Is New in MySQL 8.0, WITH), PostgreSQL documentation (WITH Queries), Microsoft Learn (WITH common_table_expression), sqlite.org (The WITH Clause, release 3.8.3).
FAQ
Is a CTE faster than a subquery?
Not by itself. PostgreSQL folds a CTE that is used once into the main query like a subquery and computes one that is used several times up front; SQL Server, according to Microsoft, runs it again for every reference. What you reliably gain is readability. Whether it gets faster only shows in your database's execution plan.
What's the difference between a CTE and a view?
A view is stored in the database and every query can use it until someone drops it. A CTE lives only inside the one statement where you write it. For a step you only need right here, the CTE is the lighter choice.
How many CTEs can I chain?
As many as the query needs. Just remember: WITH once at the start, a comma between CTEs, and no comma before the final SELECT. A CTE can read every CTE above it, but none that comes later.
Can I use the same CTE twice in the main query?
Yes, and that is one of its biggest advantages. In the second exercise you read order_totals once for the list and once for the average. If you need it twice in FROM, give each copy its own alias.