Sub topic 2
Your First CTE: Naming a Result with `WITH`
This chapter assumes you know SELECT, WHERE, JOIN, GROUP BY, and aggregate functions such as SUM and COUNT. You should also be comfortable reading a nested subquery.
A common table expression, or CTE, is a named query result that exists only while one SQL statement runs. You define a CTE with the WITH clause. The main query can then refer to the CTE by name as if it were a table.
Starting with a nested subquery
Suppose orders stores one row per order:
| customer_id | amount |
|---|---|
| 1 | 400 |
| 1 | 800 |
| 2 | 250 |
You want the names of customers whose total orders exceed 1,000. A nested subquery can calculate the totals first:
SELECT c.name, totals.total
FROM customers AS c
JOIN (
SELECT customer_id, SUM(amount) AS total
FROM orders
GROUP BY customer_id
) AS totals
ON totals.customer_id = c.id
WHERE totals.total > 1000;The inner query produces one row per customer. The outer query joins those rows to customers and filters the totals.
This query works, but the calculation is embedded inside the JOIN. As a query grows, several nested subqueries can make the order of operations difficult to follow.
Naming the result with `WITH`
A CTE moves the inner query to the beginning and gives it a meaningful name:
WITH order_totals AS (
SELECT customer_id, SUM(amount) AS total
FROM orders
GROUP BY customer_id
)
SELECT c.name, t.total
FROM customers AS c
JOIN order_totals AS t
ON t.customer_id = c.id
WHERE t.total > 1000;Read the statement in two parts:
order_totalscalculates each customer's total.- The main
SELECTjoins that named result tocustomers.
The CTE name appears after WITH. Its query is enclosed in parentheses. The main statement follows the closing parenthesis.
A CTE does not automatically create a permanent table. After this statement finishes, order_totals is no longer available.
Understanding the working model
You can think of a non-recursive CTE as a temporary named relation, meaning a table-shaped result. It has columns and rows that the rest of the statement can read.
The CTE in the example has two columns:
customer_id, copied fromorderstotal, calculated bySUM(amount)
The GROUP BY customer_id determines which rows become groups. The aggregate function calculates one total for each group.
The main query can use the CTE in places where a table is allowed, including FROM and JOIN. You can give it a short alias, such as t, just as you would give an ordinary table an alias.
Why the refactoring helps
The nested-subquery version and the CTE version return the same result. The difference is how the query communicates its structure.
| Nested subquery | CTE |
|---|---|
| The intermediate query appears inside the outer query | The intermediate query is named at the top |
| Can be concise for a small calculation | Easier to read when the calculation has a clear role |
| Becomes difficult to scan when deeply nested | Provides a natural place to add later steps |
A good CTE name describes the rows it represents. Names such as order_totals, active_customers, and monthly_revenue are usually clearer than names such as x or temp.
Reading a CTE as a pipeline step
The database processes the statement according to its SQL meaning, not necessarily in the visual order you imagine. Still, a useful reading model is:
- Build the result described by
order_totals. - Join that result to
customers. - Keep rows whose total exceeds 1,000.
- Return the selected columns.
This model helps you check whether each step produces the columns needed by the next step.
The CTE can also expose a different name for a calculated column:
WITH order_totals AS (
SELECT customer_id,
SUM(amount) AS total_amount
FROM orders
GROUP BY customer_id
)
SELECT customer_id, total_amount
FROM order_totals
WHERE total_amount >= 1000;Here, total_amount is available to the main query because the CTE gives the expression that name.
Exercise
Exercise
Refactor this query so the grouped order totals are defined as a CTE named customertotals: SELECT customerid, total FROM (SELECT customerid, SUM(amount) AS total FROM orders GROUP BY customerid) AS x WHERE total > 500;
Show answer
WITH customertotals AS (SELECT customerid, SUM(amount) AS total FROM orders GROUP BY customerid) SELECT customerid, total FROM customer_totals WHERE total > 500;