SQL CTEs: Write Readable Multi-Step Queries
CTEs (WITH clause) break complex queries into named steps. Replace nested subqueries with clean, readable, maintainable SQL.
Formula Genius can generate a draft from a plain-English prompt. Supported formulas can be checked with sample cases; review the coverage on the result.
The formula
"Find customers whose total spending is above the average customer spend"
WITH customer_totals AS (
SELECT customer_id, SUM(amount) AS total_spend
FROM orders
GROUP BY customer_id
),
avg_spend AS (
SELECT AVG(total_spend) AS avg_total
FROM customer_totals
)
SELECT ct.customer_id, ct.total_spend, a.avg_total
FROM customer_totals ct
CROSS JOIN avg_spend a
WHERE ct.total_spend > a.avg_total
ORDER BY ct.total_spend DESC;
First CTE (customer_totals) calculates each customer's total spending. Second CTE (avg_spend) calculates the average. The final SELECT joins them and filters for above-average spenders. Each step is named and readable.
Step-by-step breakdown
- WITH opens the CTE block — you can chain multiple CTEs with commas
- customer_totals groups orders by customer and sums amounts
- avg_spend calculates the average of those totals
- Final SELECT joins both CTEs and filters for above-average
- ORDER BY sorts results by spending descending
Edge cases & warnings
- CTEs are not materialized in most databases — they're re-evaluated each time referenced
- For performance on repeated references, consider a temp table instead
- Recursive CTEs need a UNION ALL and a termination condition to avoid infinite loops
- CTE names can't conflict with table names in the same query
Examples
"5 customers, average spend $500"
Returns customers spending > $500
"WITH RECURSIVE for hierarchy"
Traverses org charts, category trees
Frequently asked questions
Are CTEs faster than subqueries?
Performance is usually identical — most databases optimize them the same way. CTEs win on readability and maintainability, not speed.
Can I UPDATE using a CTE?
In PostgreSQL and SQL Server, yes. In MySQL 8+, yes with limitations. The syntax varies by database.
Can't find what you need?
Describe a formula in plain English. Formula Genius drafts and explains it, and can check supported formulas on sample cases.