Querydrill

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)

idnamecountrysignup_date
1AnnaNL2024-01-05
2BrunoBR2024-02-11
3ChloeUS2024-03-02
4DevIN2024-03-19
5ElifTR2024-05-27
6FarahUS2024-06-14
7GusNL2024-08-01
8HanaJP2024-09-09

orders (first 12 of 14 rows)

idcustomer_idorder_dateamountstatus
10112025-01-03120paid
10212025-01-2080.5paid
10322025-01-22200paid
10432025-02-0245refunded
10532025-02-15310paid
10642025-02-18150pending
10752025-03-0160paid
10862025-03-0995paid
10962025-03-30130paid
11062025-04-1175paid
11172025-04-12210paid
11212025-04-2540paid

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

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.