Common Table Expression Chained

Chain multiple CTEs for readable complex query decomposition in SQL reports.

SqlData Integrity

Code

sqlsnippet
17 lines
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-level WHERE will not work — use an outer query or a CTE.

Using it

Run the statement against the users table.

Interactive Tools for This Topic

FAQ

Which relations are involved here?
`users`, `active_users`, `orders`, `user_orders`, `ranked`, combined through a join.