Sub topic 3
Chaining Several CTEs into a Pipeline
Assume you know SELECT, WHERE, JOIN, GROUP BY, aggregate functions, and basic subqueries. This chapter uses PostgreSQL syntax for date_trunc; other databases may use a different function for grouping dates by month.
A common table expression (CTE) is a named query result created with WITH. When several CTEs appear in one statement, each later CTE can use the results produced by earlier CTEs. This creates a readable pipeline:
raw rows → grouped rows → calculated values → filtered resultRefactoring a nested query
Suppose you want monthly revenue changes. A nested query can calculate monthly revenue first and then apply a window function:
SELECT month,
revenue,
revenue - LAG(revenue) OVER (ORDER BY month) AS change
FROM (
SELECT date_trunc('month', order_date) AS month,
SUM(amount) AS revenue
FROM orders
GROUP BY date_trunc('month', order_date)
) AS monthly_sales
ORDER BY month;This query works, but the inner query is embedded inside the outer query. As the number of steps grows, nested queries become harder to scan and modify.
A CTE gives the intermediate result a name:
WITH monthly_sales AS (
SELECT date_trunc('month', order_date) AS month,
SUM(amount) AS revenue
FROM orders
GROUP BY date_trunc('month', order_date)
)
SELECT month,
revenue,
revenue - LAG(revenue) OVER (ORDER BY month) AS change
FROM monthly_sales
ORDER BY month;The name monthly_sales describes the result and makes the outer query easier to read.
Building a pipeline
Separate CTEs with commas. The next CTE can refer to any earlier CTE in the same WITH clause:
WITH monthly_sales AS (
SELECT date_trunc('month', order_date) AS month,
SUM(amount) AS revenue
FROM orders
GROUP BY date_trunc('month', order_date)
),
with_previous AS (
SELECT month,
revenue,
LAG(revenue) OVER (ORDER BY month) AS previous_revenue
FROM monthly_sales
),
classified_sales AS (
SELECT month,
revenue,
previous_revenue,
revenue - previous_revenue AS change,
CASE
WHEN previous_revenue IS NULL THEN 'first month'
WHEN revenue > previous_revenue THEN 'growing'
WHEN revenue < previous_revenue THEN 'declining'
ELSE 'unchanged'
END AS trend
FROM with_previous
)
SELECT month,
revenue,
change,
trend
FROM classified_sales
WHERE trend <> 'first month'
ORDER BY month;The stages work as follows:
monthly_salesgroups individual orders into one row per month.with_previouslooks at the preceding month's revenue.classified_salescalculates the change and assigns a label.- The final query removes the first month because it has no previous value.
Each stage has one main responsibility. This makes it easier to test a stage independently while developing the query.
Designing useful stages
A good CTE usually has a clear row meaning. For example, after monthly_sales, each row represents one calendar month. After with_previous, each row still represents one month, but it has an additional comparison value.
Before adding a CTE, ask:
- What does one row represent at this stage?
- Which columns does the next stage need?
- Can the stage be named with a short, specific noun?
- Is the calculation easier to understand when separated?
Avoid creating stages that merely rename a column without improving clarity. Also avoid hiding unrelated business rules in one large CTE.
A pipeline can include joins and filters:
WITH customer_totals AS (
SELECT customer_id,
SUM(amount) AS total
FROM orders
GROUP BY customer_id
),
ranked_customers AS (
SELECT customer_id,
total,
RANK() OVER (ORDER BY total DESC) AS sales_rank
FROM customer_totals
)
SELECT c.name,
r.total,
r.sales_rank
FROM ranked_customers AS r
JOIN customers AS c ON c.id = r.customer_id
WHERE r.sales_rank <= 10
ORDER BY r.sales_rank, c.name;Here, aggregation happens before ranking, and the customer table is joined only for the final display name.
Reading the dependency order
The order of CTEs matters. A CTE may refer to an earlier CTE, but it normally cannot refer to one written later:
WITH first_stage AS (
SELECT * FROM second_stage
),
second_stage AS (
SELECT id FROM orders
)
SELECT *
FROM first_stage;This ordering is invalid in databases that do not support forward references. Move second_stage above first_stage.
The final query can use every CTE defined in the WITH clause. A CTE that is never referenced by the final query or another CTE is unnecessary and should usually be removed.
Exercise
Exercise
Rewrite a query pipeline that first groups orders by customer, then keeps only totals above 1000, and finally joins customer names. Which CTE should perform each step?
Show answer
Use one CTE for the grouped totals, a second CTE for filtering totals above 1000, and the final SELECT for joining customer names and displaying the result.