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.
- 01Each Customer's First OrderecommerceMedium
- 02Monthly New Account Trend with CTEfinanceMedium
- 03Top Transaction Amount by Type (CTE)financeMedium
- 04Monthly Revenue Report with CTEecommerceHard
- 05Customer Lifetime Value TiersecommerceHard
- 06Repeat Purchase Rate by MonthecommerceHard
- 07Product Profit Margin RankingecommerceHard
- 08Order Fulfillment Pipeline ReportecommerceHard
- 09Month-over-Month Revenue Growth RateecommerceHard
- 10Multi-Step CTE: Customer Value TiersecommerceHard
- 11Recursive CTE: Order Value BucketsecommerceHard
- 12Customer Financial Summary with CTEfinanceHard
- 13Multi-CTE Risk ReportfinanceHard
- 14Loan Repayment Progress ReportfinanceHard
- 15Customer Lifetime Value EstimatefinanceHard
- 16Month-over-Month Transaction Growth RatefinanceHard
- 17Customer Account Summary with Multiple CTEsfinanceHard
- 18Recursive Loan Payment Schedule ProjectionfinanceHard
- 19Customer Spending by Category (CTE with Percentages)financeHard
- 20Multi-CTE Financial Health ReportfinanceHard
- 21Patient Visit Summary with CTEhealthcareHard
- 22Monthly Visit Trends with CTEshealthcareHard
- 23Department Visit Statistics with CTEhealthcareHard
- 24Billing Aging Report with Multiple CTEshealthcareHard
- 2530-Day Readmission Rate by DepartmenthealthcareHard
- 26Patient Journey Summary with CTEshealthcareHard
- 27Doctor Revenue Ranking by Department (CTE + Window)healthcareHard
- 28Executive Dashboard Metrics with CTEshealthcareHard
- 29Patient Visit Summary with Diagnosis Counts and BillinghealthcareHard
- 30Department Composite Performance RankinghealthcareHard
- 31Complete Patient Journey TimelinehealthcareHard
- 32Patient Cohort Retention AnalysishealthcareHard
- 33Doctor Revenue-to-Salary Efficiency RatiohealthcareHard
- 34Hospital KPI Dashboard with Multiple CTEshealthcareHard