26. WITH: naming the steps of a query
Common table expressions: break a long query into named steps that read from the top down.
A query in steps
Some questions take several steps: first work out each order's total, then pick the big ones, then find who placed them. With subqueries the steps nest inside each other, and you read the query from the inside out. Here are the orders worth 300 baht or more, written with a subquery in FROM:
SELECT order_id, total
FROM (
SELECT order_id, SUM(qty * price) AS total
FROM order_item
GROUP BY order_id
)
WHERE total >= 300
ORDER BY total DESC, order_id;| order_id | total |
|---|---|
| 9 | 490.0 |
| 8 | 390.0 |
| 15 | 375.0 |
| 4 | 300.0 |
| 11 | 300.0 |
WITH lets you take the inner step out, give it a name, and put it first:
WITH order_total AS (
SELECT order_id, SUM(qty * price) AS total
FROM order_item
GROUP BY order_id
)
SELECT order_id, total
FROM order_total
WHERE total >= 300
ORDER BY total DESC, order_id;| order_id | total |
|---|---|
| 9 | 490.0 |
| 8 | 390.0 |
| 15 | 375.0 |
| 4 | 300.0 |
| 11 | 300.0 |
The same 5 rows. WITH name AS (SELECT ...) makes a common table expression (CTE): a named result that the statement after it can use like a table. Now the query reads like a recipe: "first, order_total is each order's total; then, from order_total, take those of 300 or more".
A CTE lives only as long as its statement. It is not saved in the database: the next statement can't see order_total (for a query you want to keep, a view is the tool, chapter 30).
Several steps one after another
After WITH come as many steps as you like, separated by commas, and each step can use the ones before it. Who are the best customers, counting only orders that weren't cancelled?
WITH
kept AS (
SELECT id, customer_id FROM orders WHERE status <> 'cancelled'
),
order_total AS (
SELECT order_id, SUM(qty * price) AS total
FROM order_item
GROUP BY order_id
),
spent AS (
SELECT k.customer_id, COUNT(*) AS orders, SUM(t.total) AS spent
FROM kept AS k JOIN order_total AS t ON t.order_id = k.id
GROUP BY k.customer_id
)
SELECT c.name, s.orders, s.spent
FROM spent AS s JOIN customer AS c ON c.id = s.customer_id
ORDER BY s.spent DESC, c.name
LIMIT 5;| name | orders | spent |
|---|---|---|
| Wichai Saelim | 2 | 865.0 |
| Kanya Boonmee | 2 | 480.0 |
| Malee Srisuk | 2 | 400.0 |
| Somchai Jaidee | 3 | 400.0 |
| Anan Wongsa | 1 | 300.0 |
Read it from the top, one name at a time:
kept: the orders that weren't cancelled.order_total: each order's total.spent: for each customer, how many kept orders and how much in all (it useskeptandorder_total).- The last
SELECTputs the names on and takes the top five.
Each step can be checked alone: put SELECT * FROM kept after the WITH part and run it. When a long query gives a wrong answer, that is how you find the step that went wrong.
Give the steps names that say what one row is: order_total, spent, kept. A query of named steps is easy to read a month later; t1, t2, t3 are not.
Using a step twice
A subquery written in two places has to be written (and kept right) twice. A CTE is written once and used as often as you like. Which orders are worth more than the average order?
WITH order_total AS (
SELECT order_id, SUM(qty * price) AS total
FROM order_item
GROUP BY order_id
)
SELECT order_id, total,
(SELECT round(AVG(total), 2) FROM order_total) AS average
FROM order_total
WHERE total > (SELECT AVG(total) FROM order_total)
ORDER BY total DESC, order_id;| order_id | total | average |
|---|---|---|
| 9 | 490.0 | 229.33 |
| 8 | 390.0 | 229.33 |
| 15 | 375.0 | 229.33 |
| 4 | 300.0 | 229.33 |
| 11 | 300.0 | 229.33 |
| 6 | 290.0 | 229.33 |
| 7 | 235.0 | 229.33 |
order_total is used three times: as the table in FROM, and in two subqueries working out the average. 7 of the 15 orders are above the average of 229.33.
A CTE can name its columns in brackets after its name, and its rows can come from VALUES. That makes a small table right inside the query, handy for a list of things to look for:
WITH wanted (city) AS (VALUES ('Phuket'), ('Khon Kaen'))
SELECT c.name, c.city
FROM customer AS c JOIN wanted AS w ON w.city = c.city
ORDER BY c.city, c.name;| name | city |
|---|---|
| Narin Thongdee | Khon Kaen |
| Tawan Rungruang | Khon Kaen |
| Pim Chaiya | Phuket |
| Siriporn Kaewdee | Phuket |
WITH before INSERT, UPDATE and DELETE
WITH can also stand in front of a statement that changes data: its steps can then be used in the SELECT of an INSERT, or in the WHERE and SET of an UPDATE or DELETE. Phai SQL takes it just as SQLite does.
The shop wants a table of VIP customers: those who have spent 300 baht or more.
CREATE TABLE vip (
customer_id INTEGER PRIMARY KEY REFERENCES customer(id),
spent REAL NOT NULL
);
WITH spent AS (
SELECT o.customer_id, SUM(i.qty * i.price) AS spent
FROM orders AS o JOIN order_item AS i ON i.order_id = o.id
WHERE o.status <> 'cancelled'
GROUP BY o.customer_id
)
INSERT INTO vip (customer_id, spent)
SELECT customer_id, spent FROM spent WHERE spent >= 300;
SELECT * FROM vip;| customer_id | spent |
|---|---|
| 1 | 400.0 |
| 2 | 400.0 |
| 3 | 300.0 |
| 6 | 480.0 |
| 7 | 865.0 |
| 8 | 300.0 |
Restock the best sellers: every product with 10 or more sold gets 50 more in stock:
WITH sold AS (
SELECT product_id, SUM(qty) AS qty
FROM order_item
GROUP BY product_id
)
UPDATE product SET stock = stock + 50
WHERE id IN (SELECT product_id FROM sold WHERE qty >= 10);
SELECT id, name, stock FROM product WHERE id IN (7, 10, 11);| id | name | stock |
|---|---|---|
| 7 | Potato Chips | 250 |
| 10 | Notebook | 125 |
| 11 | Pen | 350 |
And take off the VIP list anyone who has cancelled an order:
WITH cancelled AS (
SELECT DISTINCT customer_id FROM orders WHERE status = 'cancelled'
)
DELETE FROM vip
WHERE customer_id IN (SELECT customer_id FROM cancelled);
SELECT * FROM vip;| customer_id | spent |
|---|---|
| 1 | 400.0 |
| 2 | 400.0 |
| 6 | 480.0 |
| 7 | 865.0 |
| 8 | 300.0 |
Anan (customer 3) cancelled order 14, so he is gone from the list; 5 VIPs are left.
Don't give a step the same name as the table that the UPDATE or DELETE changes (WITH product AS (...) UPDATE product ...). Which product does each part mean? SQLite always changes the real table and reads the step elsewhere, which is easy to misread; Phai SQL refuses the statement. Give the step its own name, such as sold or cancelled above.
When to use WITH
- A query has steps: a total, then a filter on it, then a join. Name each step.
- The same subquery is needed twice or more.
- A query has grown hard to read: rewriting its subqueries as CTEs, from the inside out, is often the quickest way to understand it.
For one short subquery, WITH adds nothing; WHERE id IN (SELECT ...) is fine. And WITH has one more power, a step that uses itself, which the next chapter is about.
- With a CTE, work out how many items (the sum of
qty) each category has sold, with the category's name. - Using one CTE twice, list the products whose price is above the average price.
- With
WITH ... UPDATE, mark every order of a VIP customer that is stillpaidasshipped. How many orders change?
Show the answer
WITH sold AS (
SELECT p.category_id, SUM(i.qty) AS items
FROM order_item AS i JOIN product AS p ON p.id = i.product_id
GROUP BY p.category_id
)
SELECT c.name, s.items
FROM sold AS s JOIN category AS c ON c.id = s.category_id
ORDER BY s.items DESC;
WITH priced AS (SELECT id, name, price FROM product)
SELECT name, price FROM priced
WHERE price > (SELECT AVG(price) FROM priced)
ORDER BY price DESC;
WITH big AS (SELECT customer_id FROM vip)
UPDATE orders SET status = 'shipped'
WHERE status = 'paid' AND customer_id IN (SELECT customer_id FROM big);| name | items |
|---|---|
| Stationery | 53 |
| Snacks | 17 |
| Drinks | 14 |
| Bakery | 12 |
| name | price |
|---|---|
| Cashew Nuts | 150.0 |
| Cheesecake | 120.0 |
| Dried Mango | 90.0 |
| Banana Bread | 60.0 |
Phai (bamboo), given as a gift of knowledge: free to use, learn from and pass on · every example on this page was run on Phai SQL and checked against SQLite when the page was made