Common Table Expression Chained
Chain multiple CTEs for readable complex query decomposition in SQL reports.
Code
WITH active_users AS (
SELECT id, name FROM users WHERE status = 'active'
),
user_orders AS (
SELECT u.id, u.name, COUNT(o.id) AS order_count
FROM active_users u
LEFT JOIN orders o ON o.user_id = u.id
GROUP BY u.id, u.name
),
ranked AS (
SELECT *, RANK() OVER (ORDER BY order_count DESC) AS rnk
FROM user_orders
)
SELECT id, name, order_count
FROM ranked
WHERE rnk <= 10
ORDER BY rnk;What the code does
The statement is SELECT, touching users, active_users, orders, user_orders and ranked.
The SQL constructs in play: a CTE (WITH … AS) that names an intermediate result before the main query; one JOIN combining rows across tables; a WHERE clause constraining which rows the statement operates on; COUNT aggregation; a GROUP BY that collapses matching rows into one output row per group; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order.
What to watch for
- Window functions evaluate after
WHERE/GROUP BY, so filtering on their output in the same-levelWHEREwill not work — use an outer query or a CTE.
Using it
Run the statement against the users table.
Interactive Tools for This Topic
Cron Expression ExplainerParse a five-field cron expression and get a field-by-field plain-English explanation plus a one-line human-readable schedule summary.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Which relations are involved here?
- `users`, `active_users`, `orders`, `user_orders`, `ranked`, combined through a join.
Report a problem with this exampleOpens a pre-filled issue on GitHub.