SQL subquery practice problems
A subquery is a query used inside another one: as a single value to compare with, as a list for IN, as a table in FROM, or as a test with EXISTS. Above the average, never ordered, the latest per group and second highest are all subquery questions.
The problems include correlated subqueries, where the inner query depends on the current outer row, and NOT IN against a column with NULLs, which fails in a way worth seeing once.
Try one here: Customers who never had a refund
Try it yourself
Return the names of customers who placed at least one order and never had an order with the status refunded.
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.
Joins
- Customers who never had a refundReturn the names of customers who placed at least one order and never had an order with the status refunded.
- Employees who manage nobodyReturn the names of employees who do not manage anyone: no other employee has them as manager.
- Revenue inflated by a join (fan-out)For each customer with at least one paid order (status paid), return the name, the total amount of their paid orders and the total quantity of items on those orders. An order without item lines counts with quantity 0. Customer names are unique.
Advanced
- Above the average salaryReturn the names of employees who earn more than the average salary of all employees.
- Top earner per departmentReturn the dept_id, name and salary of the highest-paid employee in each department. If several employees share the top salary in a department, return all of them. Ignore employees without a department.
- Second highest salaryReturn the second highest salary as a single value. If several employees share the top salary, the second highest is the next lower salary.
- 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.
- Share of revenueFor each country, return the country and its share of total paid revenue in percent, rounded to 1 decimal.
- Each customer's first orderFor each customer, return the customer_id and the id of their first order (earliest date, then lowest id). Count every order, whatever the status.
- 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.
- Orders above the customer's averageReturn the id of every paid order whose amount is above the average amount of that same customer's paid orders.
- 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.
- Two largest paid orders per customer (LATERAL)For each customer with paid orders, return the customer's name and the id and amount of their two largest paid orders (highest amount first, then lowest id). A customer with one paid order returns one row.
- Most orders, ties includedWhich customers placed the most orders, counting orders of every status? Return the name and the number of orders of every customer who shares first place. Customer names are unique.
- Price at the time of the orderprice_history holds the price of a product from each valid_from date onward. For every order line of a product that has a price on the order date, return the order id, the product id and the price that was valid on the order date. A price counts from its valid_from date itself.
Interview classics
- Third highest salaryReturn the third highest distinct salary as a single value.
- Second highest salary per departmentFor each department with at least two different salaries, return the dept_id and its second highest salary. Ignore employees without a department.
- Departments above averageReturn the dept_id and average salary of every department whose average salary is above the average salary of all employees. Ignore employees without a department when grouping.
- 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.
- First order not paidReturn the names of customers whose first order (earliest date, then lowest id) has a status other than paid.
- 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.
- Sessions per user (30-minute rule)A new session starts with a user's first event, and again whenever more than 30 minutes have passed since that user's previous event. Return each user_id with their number of sessions.
- 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.
- Reactivated subscribersThe end date is the first day without the subscription, so a new subscription that starts on the previous end date is a plan change with no gap. A reactivation is a subscription whose start date is later than the end date of the same user's previous subscription. A user's subscriptions never overlap. Return the user_id, the start date of each reactivation, and the gap in days: that start date minus the previous end date.
- 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.
- Peak number of bookings at onceA booking occupies its room from check_in up to, but not including, check_out. Return one number: the highest number of bookings that are in the hotel at the same time, over all rooms.
Work mode
- Keep one account per personFrom Sam in Support: "For everyone who signed up more than once with the same email typed differently, I only want their earliest signup. The signup dates come in mixed formats, and if two signups fall on the same day the lowest id wins. Send me one row per person." Return the id of the account to keep and the email in lowercase with no spaces around it.
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.
- Product performance, step 4: products with no paid salesClose the review with the dead stock. Return the name of every product that has never been part of a paid order.
- Payroll review, step 2: pay against the company averageWhich departments pay above the company average? For every department that has employees, return the department name, its average salary rounded to a whole number, and the difference between that average and the average salary of all employees, also rounded to a whole number. All employees means everyone, including those without a department.
- Payroll review, step 3: the top earner's shareHow concentrated is the pay? For each department, return the department name, the name of its highest-paid employee and that salary as a percentage of the department's total salary, rounded to 1 decimal. If several employees share the top salary, return each of them.
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.