Before you start, you need
Answer questions with subqueries · Filter groups with HAVING
Give an intermediate result a name
A long query is easier to follow if you split off a step and give it a name. For example, you can call shipped the list of orders with that status, and then query that list.
WITH defines that result with a name. This tool is called a CTE, short for common table expression. Write the name, AS and the query in parentheses; then comes the query that uses it.
The name is used in FROM just like a table name. Choose one that explains its rows: shipped contains orders and customer_totals would hold a summary per customer. That way you know what you are reading at each step.
The CTE exists only for that statement. It does not store a new table you can open in another run. To check the intermediate step, run the query that defines it and check its rows before carrying on.
WITH name AS (SELECT ... FROM ...)
SELECT ... FROM name;See it in action
We want to prepare the shipped orders and read that result.
WITH shipped AS (
SELECT id, total
FROM orders
WHERE status = 'shipped'
)
SELECT id, total
FROM shipped;| id | total |
|---|---|
| 101 | 128.4 |
| 104 | 179 |
| 106 | 1088 |
| 107 | 36.9 |
| 110 | 61.5 |
| 112 | 54 |
| 113 | 98 |
| 115 | 24 |
- WITH defines shipped as the result of the filter. Each row is still one order.
- The outer query reads id and total from shipped just as it would read those columns from a table.
- The name exists only during this statement. A separate query cannot use shipped.
- Once the input has been checked, you can summarise it in the outer query. If a summary fails, first check which rows the CTE supplied.
Practice with help
Getting things wrong is part of learning: you can run your query as many times as you like and nothing is lost. If you get stuck, open a hint (each one reveals a bit more) and save the solution for last.
Guided practice
First, a minimal CTE
Create a CTE called shipped with id and total for the shipped orders. Return id and total from that CTE.
Expected result: 9 rows with the columns id, total, in that order. Row order does not matter.
View tables and data
Open this panel to see the full data.
Start with a list of shipped orders.
Name that query with WITH and read it from the outer query.
The shipped CTE must supply id and total.
Solution explained
WITH shipped AS (SELECT id, total FROM orders WHERE status = 'shipped') SELECT id, total FROM shipped;The outer query reads a result with one row per shipped order. The CTE exists only in this statement.
Use a named summary
Guided practice
Use a named summary
Prepare the non-cancelled orders in a CTE called valid_orders. Then summarise and filter that result using these rules:
- The CTE returns customer_id and total for orders whose status is not cancelled.
- Group by customer_id and show customer_id and the sum of total, rounded to two decimal places, with the alias valid_total.
- Keep only the customers whose sum is at least 200.
- Sort by valid_total from highest to lowest, and by customer_id from lowest to highest when there is a tie.
Expected result: 5 rows with the columns customer_id, valid_total, in that order. Keep the row order requested.
View tables and data
Open this panel to see the full data.
Prepare the valid orders before adding up their amounts per customer.
The outer query groups by customer_id and uses SUM(total).
Filter the groups with HAVING SUM(total) >= 200 and sort by the alias, descending.
Solution explained
WITH valid_orders AS (
SELECT customer_id, total
FROM orders
WHERE status <> 'cancelled'
)
SELECT customer_id,
ROUND(SUM(total), 2) AS valid_total
FROM valid_orders
GROUP BY customer_id
HAVING SUM(total) >= 200
ORDER BY valid_total DESC, customer_id;The CTE provides a clean input for the aggregate. The outer query groups, filters the groups and sets the final order.
Your turn
Solve this variation. Spot the part that has changed before you look for help.
Practice
Then another summary
Use a CTE called valid with customer_id and total for non-cancelled orders. Return customer_id and COUNT(*) as orders per customer.
Expected result: 10 rows with the columns customer_id, orders, in that order. Row order does not matter.
View tables and data
Open this panel to see the full data.
Define the input before summarising it.
The outer query groups the CTE rows by customer.
The alias required for the count is orders.
Solution explained
WITH valid AS (SELECT customer_id, total FROM orders WHERE status <> 'cancelled') SELECT customer_id, COUNT(*) AS orders FROM valid GROUP BY customer_id;Separating filtering from counting makes the change in unit clear: from order to customer.
Key takeaways
- WITH names an intermediate result.
- The outer query can read it.
- A CTE lasts for one statement.