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_idproduct_idquantityunit_price
10011404.79
10013252.79
10016424.9
1002223.49
10021035.49
10031604.69
100311684.9
10033502.59
100443179
100493269
100551449
10061304.79
10067106.99
100782219
100711489.9
10071204.99
100846175
1008253.49
1009101204.99
10092403.19
100992279
1010726.99
1010213.49
1011121129
10111104.99
10113122.79
10126823.9
10121404.69
101391279
101452439
101442179
10151504.79
101511289.9
10161045.49
1017233.49
1017726.99
10181804.79
101861024.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;
nameunits_sold
Copy paper, 500 sheets330
Notebook A5, ruled127
Lever arch file, gray87
Blue ballpoint pens, 10-pack51
Black ink cartridge22

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);
categoryavg_price
Electronics209
Furniture319

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_idproduct_idquantityunit_price
10011404.79
10013252.79
10016424.9
1002223.49
10021035.49
10031604.69
100311684.9
10033502.59
100443179
100493269
100551449
10061304.79
10067106.99
100782219
100711489.9
10071204.99
100846175
1008253.49
1009101204.99
10092403.19
100992279
1010726.99
1010213.49
1011121129
10111104.99
10113122.79
10126823.9
10121404.69
101391279
101452439
101442179
10151504.79
101511289.9
10161045.49
1017233.49
1017726.99
10181804.79
101861024.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;
namestockunits_sold
Yellow sticky notes, 12 pads014
Comfort office chair1211
27-inch monitor156
Standing desk53
Mono laser printer L3082
Cross-cut shredder01

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_idproduct_idquantityunit_price
10011404.79
10013252.79
10016424.9
1002223.49
10021035.49
10031604.69
100311684.9
10033502.59
100443179
100493269
100551449
10061304.79
10067106.99
100782219
100711489.9
10071204.99
100846175
1008253.49
1009101204.99
10092403.19
100992279
1010726.99
1010213.49
1011121129
10111104.99
10113122.79
10126823.9
10121404.69
101391279
101452439
101442179
10151504.79
101511289.9
10161045.49
1017233.49
1017726.99
10181804.79
101861024.9
orders 18 rows, 5 columns
order_idcustomer_idorder_datestatusemployee_id
100112026-01-08delivered3
100242026-01-12delivered4
100332026-01-20delivered3
100472026-02-03delivered4
100522026-02-11cancelled8
100612026-02-25delivered3
1007102026-03-04delivered2
100852026-03-17delivered4
100982026-03-30delivered3
101062026-04-07delivered8
1011122026-04-22delivered4
101232026-05-06delivered3
101392026-05-19cancelled8
101472026-06-02shipped4
101512026-06-10shipped3
1016112026-06-12openNULL
101742026-06-13openNULL
1018102026-06-14openNULL
customers 12 rows, 7 columns
customer_idnamecitycountrycustomer_sincesegmentphone
1Harbor Fremont PartnersBostonUSA2021-03-15Business617-555-0142
2Emily CarterChicagoUSA2022-07-01ConsumerNULL
3Riverside County OfficeRiversideUSA2020-11-20Government951-555-0110
4Raj PatelLeedsUK2023-01-09Consumer0113 496 0123
5Lakeview Hotel LtdManchesterUK2022-04-18Business0161 496 0456
6Olivia BrooksAustinUSA2024-02-27ConsumerNULL
7Greene & Shaw LLPLondonUK2021-09-05Business020 7946 0321
8Maple Grove High SchoolAustinUSA2023-08-14School512-555-0187
9Chloe EvansBostonUSA2025-05-30Consumer617-555-0199
10Northline Printing CoTorontoCanada2020-06-12Business416-555-0133
11Daniel KimSeattleUSA2024-10-03ConsumerNULL
12Westbrook Dental ClinicChicagoUSA2022-12-01Business312-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:

DatabaseRecursionWorth knowing
MySQLWITH RECURSIVE, required as soon as one CTE is recursiverepeating WITH for the second CTE is explicitly not allowed
PostgreSQLWITH RECURSIVEa 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 Serverno 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 RECURSIVEMATERIALIZED 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.

Up next: window functions

Number rows, hand out ranks, find the two most expensive products in each category: ROW_NUMBER, RANK and PARTITION BY calculate across rows without collapsing them. You'll use the CTE from this lesson again right away.

Practice window functions

Write to us

Choose language

Select your preferred language