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_idtotal
9490.0
8390.0
15375.0
4300.0
11300.0
5 rows

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_idtotal
9490.0
8390.0
15375.0
4300.0
11300.0
5 rows

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;
nameordersspent
Wichai Saelim2865.0
Kanya Boonmee2480.0
Malee Srisuk2400.0
Somchai Jaidee3400.0
Anan Wongsa1300.0
5 rows

Read it from the top, one name at a time:

  1. kept: the orders that weren't cancelled.
  2. order_total: each order's total.
  3. spent: for each customer, how many kept orders and how much in all (it uses kept and order_total).
  4. The last SELECT puts 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_idtotalaverage
9490.0229.33
8390.0229.33
15375.0229.33
4300.0229.33
11300.0229.33
6290.0229.33
7235.0229.33
7 rows

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;
namecity
Narin ThongdeeKhon Kaen
Tawan RungruangKhon Kaen
Pim ChaiyaPhuket
Siriporn KaewdeePhuket
4 rows

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_idspent
1400.0
2400.0
3300.0
6480.0
7865.0
8300.0
6 rows

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);
idnamestock
7Potato Chips250
10Notebook125
11Pen350
3 rows

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_idspent
1400.0
2400.0
6480.0
7865.0
8300.0
5 rows

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

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.

  1. With a CTE, work out how many items (the sum of qty) each category has sold, with the category's name.
  2. Using one CTE twice, list the products whose price is above the average price.
  3. With WITH ... UPDATE, mark every order of a VIP customer that is still paid as shipped. 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);
nameitems
Stationery53
Snacks17
Drinks14
Bakery12
4 rows
nameprice
Cashew Nuts150.0
Cheesecake120.0
Dried Mango90.0
Banana Bread60.0
4 rows

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