Create a named subquery for readability and reuse.
Section: Common Table Expressions
Basic CTE
sql
sql
WITH recent_orders AS (
SELECT *
FROM orders
WHERE created_at >= CURRENT_DATE - INTERVAL "30 days"
)
SELECT customer_id, COUNT(*) AS total_recent_orders
FROM recent_orders
GROUP BY customer_id;Explanation
CTEs make multi-step queries easier to read and maintain.
Learn the surrounding workflow
Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.
Related commands
Same sheet · prioritizing Common Table Expressions