SQL CTE (WITH clause) practice problems
A common table expression names a step: WITH monthly AS (...) SELECT ... FROM monthly. It makes a long query readable from top to bottom and lets a later step reuse an earlier one.
These problems are multi-step by nature: aggregate first and then compare, rank and then filter, or walk a reporting chain with a recursive CTE.
Try one here: Big spenders
Try it yourself
Calculate each customer's total paid spend, then return the names of customers whose total is above the average of those totals. Only customers with at least one paid order count in the average.
customers (8 rows)
| id | name | country | signup_date |
|---|---|---|---|
| 1 | Anna | NL | 2024-01-05 |
| 2 | Bruno | BR | 2024-02-11 |
| 3 | Chloe | US | 2024-03-02 |
| 4 | Dev | IN | 2024-03-19 |
| 5 | Elif | TR | 2024-05-27 |
| 6 | Farah | US | 2024-06-14 |
| 7 | Gus | NL | 2024-08-01 |
| 8 | Hana | JP | 2024-09-09 |
orders (first 12 of 14 rows)
| id | customer_id | order_date | amount | status |
|---|---|---|---|---|
| 101 | 1 | 2025-01-03 | 120 | paid |
| 102 | 1 | 2025-01-20 | 80.5 | paid |
| 103 | 2 | 2025-01-22 | 200 | paid |
| 104 | 3 | 2025-02-02 | 45 | refunded |
| 105 | 3 | 2025-02-15 | 310 | paid |
| 106 | 4 | 2025-02-18 | 150 | pending |
| 107 | 5 | 2025-03-01 | 60 | paid |
| 108 | 6 | 2025-03-09 | 95 | paid |
| 109 | 6 | 2025-03-30 | 130 | paid |
| 110 | 6 | 2025-04-11 | 75 | paid |
| 111 | 7 | 2025-04-12 | 210 | paid |
| 112 | 1 | 2025-04-25 | 40 | paid |
Free, no account needed. PostgreSQL runs in your browser and your answer is checked again on changed data.
Advanced
- Big spendersCalculate each customer's total paid spend, then return the names of customers whose total is above the average of those totals. Only customers with at least one paid order count in the average.
- Levels in the reporting chainReturn each employee's name and their level in the reporting chain: 1 for employees without a manager, 2 for the people who report to them, 3 for the level below that, and so on.
- Month over monthReturn each month (like 2025-01), its paid revenue, and the change from the previous month's paid revenue. The first month shows NULL for the change.
- Top two per categoryFor each category, return the category, product name and revenue (quantity times price) of its two best-selling products by revenue.
- Cumulative share of revenueReturn each sold product with its revenue (quantity times price) and the cumulative share of total revenue in percent, rounded to 1 decimal, going from the product with the most revenue to the least. Order by revenue descending, then by product name. The last row shows 100.
Interview classics
- Repeat purchase rateOf all customers who placed at least one order, what percentage placed two or more orders, whatever the status? Return a single number rounded to 1 decimal.
- Median salaryReturn the median salary of all employees as a single value: the middle salary when they are sorted, or the average of the two middle salaries when the number of employees is even.
- Orders in consecutive monthsReturn the customer_id of every customer who placed orders in two calendar months in a row, for example March and April, whatever the status. Each customer appears once.
- Runs of the same statusGo through the orders by id and group consecutive orders that share the same status into runs. For each run, return the status, the first order id, the last order id and the number of orders in the run.
- Cohort retentionGroup customers by the month of their first order, like 2025-01, counting every order whatever the status. For each such month return the month, the number of customers who first ordered in it, and how many of those customers ordered again in a later month.
- Signup to purchase conversionA user converted when they have a purchase that is later than their first signup. Return one row: the number of users who signed up, the number of those who converted, and the conversion rate as a percentage rounded to 1 decimal.
- New and returning users per dayA user is new on the first day they have any event and returning on every later day they are active. Return every day that has events, as a date, with the number of new users and the number of returning users on that day.
- Day-1 retentionA user is retained on day 1 when they have an event on the calendar day right after their first active day. Every user counts in the total, also a user whose first day is the last day in the data. Return one row: the number of users, the number retained on day 1, and the retention rate as a percentage rounded to 1 decimal.
- Retention curveFor each number of days since a user's first active day, from 0 to 7, return that number and how many users were active that many days after their first day. Day 0 is the first day itself. Leave out day numbers on which nobody was active.
- Rolling 7-day active usersFor every day that has events, return the day, as a date, and the number of different users with an event in the 7 days ending on that day (that day and the 6 days before it).
- Longest streak of active daysReturn each user_id with the length of their longest run of consecutive active days. A user who was never active two days in a row has a streak of 1.
- Monthly churn rateA user is active on a day when one of their subscriptions started on or before that day and has no end date or an end date after that day. Return one row for March 2025: the number of users active on 2025-03-01, how many of them were no longer active on 2025-04-01, and that share as a percentage rounded to 1 decimal.
- Merge bookings into occupied periodsFor each room, merge bookings that overlap or touch (one ends on the day the next starts) into one occupied period. Return the room, the first check_in and the last check_out of every period.
Case studies
- Revenue report, step 2: change on the previous monthExtend the monthly report. For each month return month, revenue, the previous month's revenue as prev_revenue, and the difference as change (revenue minus prev_revenue). The first month has no previous month, so both extra columns are NULL there.
- Revenue report, step 3: running totalAdd a year-to-date column. For each month return month, revenue and running_total: the sum of paid revenue from the first month up to and including that month.
- Revenue report, step 4: share of the totalFinish the report. For each month return month, revenue and share_pct: that month's percentage of all paid revenue, rounded to 1 decimal.
- Customer value, step 3: segment the customersLabel each customer with at least one paid order. Return name, total (their paid spend) and segment: 'high' for 400 or more, 'mid' for 150 or more, otherwise 'low'.
- Customer value, step 4: summarize the segmentsRoll the segments up. For each segment from step 3 return segment, the number of customers in it as customers, and their combined paid spend as revenue.
- Product performance, step 3: best seller in each categoryFor each category, return category, name and revenue of the product with the highest paid revenue in that category.
Read first if you are stuck
Other practice sets
Your first 8 exercises are free, with no account. Every answer is checked on the rows you see and again on changed data.