Back to Learn SQL
Advanced SQLAdvanced11 min
Common Table Expressions (CTE)
Break complex logic into understandable steps with WITH clauses.
What You Will Learn
- CTEs improve readability in multi-step transformations.
- Reuse intermediate datasets inside one query.
- Good naming for CTEs makes maintenance much easier.
Sample SQL
WITH paid_orders AS (
SELECT user_id, total_amount
FROM orders
WHERE status = 'paid'
)
SELECT user_id, SUM(total_amount) AS revenue
FROM paid_orders
GROUP BY user_id;Next Step
Try rewriting this query in your own schema, then use our tools to format and refine it.