Skip to main content

Chapter 7 · CTEs

SQL CTE Practice

A CTE (common table expression) names an intermediate result with WITH, so a long query reads like steps: first compute monthly revenue, then rank the months, then pick the best one.

CTEs are how experienced analysts keep complex queries readable, and recursive CTEs can walk hierarchies or generate series of dates.

Start practising34 exercises · 0 easy, 3 medium, 31 hard

Key ideas

WITH name AS (…)
Define a named result you can select from in the main query.
Several CTEs
Chain them with commas; each can use the ones defined before it.
CTE vs subquery
Same power, better readability, and a CTE can be referenced more than once.
Recursive CTE
WITH RECURSIVE repeats a step until it stops producing rows: hierarchies and date series.

Example: The three best months by revenue

WITH monthly AS (
  SELECT strftime('%Y-%m', order_date) AS month,
         SUM(total_amount) AS revenue
  FROM orders
  WHERE status <> 'cancelled'
  GROUP BY month
)
SELECT month, revenue
FROM monthly
ORDER BY revenue DESC
LIMIT 3;

Step one builds a small monthly table; step two only has to sort it.

In interviews

For multi-step questions, start by writing the CTE names as a plan ("monthly revenue, then ranked"). Interviewers care about your structure as much as the result.

All 34 CTEs exercises

Ordered from easiest to hardest. Each one runs on a real database with instant feedback.