SQL Common Table Expressions (CTEs)
A CTE (WITH) names an intermediate result so you can build a complex query as a sequence of clear steps.
A common table expression (CTE) names a query in a
WITH
block, and the statement underneath selects from that name as if it were a
table. It lasts for the one statement only.
with monthly as (
select date_trunc('month', o.order_date) as m,
sum(oi.quantity * oi.unit_price) as revenue
from orders as o
join order_items as oi on oi.order_id = o.order_id
group by m
)
select m, revenue
from monthly
order by m
Here
monthly
is the CTE. You are about to write one of these against Garden Shop, so the
habit worth carrying in is the naming: call it for the result it produces.
order_revenue
reads better in the outer query than
cte1, because the query then looks like it is selecting from a real table.
Schema · Garden Shop Tables · order_items, orders, customers 3 tables
One row per line item within an order.
One row per order. Unshipped orders have a null shipped_date.
One row per customer. Some customers have no phone on file.
Find the top 5 customers by lifetime revenue. Use a
WITH block to total each customer's revenue, then join
customers for their names and return first_name, last_name, and lifetime_revenue, biggest
spender first.
Run your query to inspect the result.
Expected answer
- Columns: first_name, last_name, lifetime_revenue.
- Rows: the top 5 customers by total spend.
- The CTE computes revenue per customer; the outer query adds names and ranks them.
Related
Searched and simple CASE patterns.
Searched and simple CASE, plus conditional aggregation.
Practice WITH clauses and step-by-step reports.
The default RANGE frame groups tied rows; use ROWS.
WHERE is evaluated before SELECT aliases exist.
The WITH clause, chained steps, and CTE vs subquery.