SQL window function practice problems
Window functions compute a value across related rows without collapsing them: a running total, a rank inside each department, the previous order of the same customer, a share of the total.
The problems cover PARTITION BY, ORDER BY inside OVER, ranking functions, LAG and LEAD and moving frames. They are the most common advanced topic in analyst interviews, so they are worth repeating until the pattern is automatic.
Try one here: Rank within department
Try it yourself
Return each employee's name, dept_id and their salary rank inside their own department, where 1 is the highest salary.
employees (11 rows)
| id | name | dept_id | salary | hire_date | manager_id |
|---|---|---|---|---|---|
| 1 | Ava | 2 | 130000 | 2019-03-15 | NULL |
| 2 | Ben | 2 | 105000 | 2020-07-01 | 1 |
| 3 | Cleo | 1 | 82000 | 2021-01-10 | 7 |
| 4 | Dan | 1 | 76000 | 2022-05-23 | 7 |
| 5 | Eve | 3 | 54000 | 2022-09-12 | 11 |
| 6 | Finn | 2 | 98000 | 2021-11-30 | 1 |
| 7 | Gia | 1 | 99000 | 2018-06-04 | NULL |
| 8 | Hugo | 3 | 61000 | 2020-02-18 | NULL |
| 9 | Iris | 4 | 88000 | 2019-10-07 | NULL |
| 10 | Jack | 4 | 72000 | 2023-04-17 | 9 |
| 11 | Kai | NULL | 50000 | 2024-01-08 | 8 |
Free, no account needed. PostgreSQL runs in your browser and your answer is checked again on changed data.
Advanced
- Rank within departmentReturn each employee's name, dept_id and their salary rank inside their own department, where 1 is the highest salary.
- Running revenue totalFor every paid order, return the order id and the running total of paid revenue, ordered by order date and then by id.
- Running total per customerFor every order, return the order id, the customer_id and the running total of that customer's order amounts, in order of date and then id. Count every order, whatever the status.
- 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.
- Dense rankReturn every employee's name, salary and DENSE_RANK of the salary across the whole company, where 1 is the highest.
- Change from the previous orderFor every paid order, return the id and the difference between its amount and the amount of the previous paid order, ordered by order date then id. The first order shows NULL.
- Days until the next orderFor every order, return the order id and the number of days until the same customer's next order (by date, then id), as a whole number. A customer's last order shows NULL. Count every order, whatever the status. In PostgreSQL, subtracting one date from another gives the number of days.
- Moving averageGo through the paid orders by date and then id. For each one, return the id and the average amount of that order and the two paid orders before it, rounded to 2 decimals. The first two rows average over fewer orders.
- Share of the customer's totalFor every paid order, return the id and its share of that customer's total paid amount in percent, rounded to 1 decimal. A customer with one paid order shows 100.
- 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.
- Compared to the first orderFor every order, return the order id, the customer_id and the difference between its amount and the amount of that customer's first order (earliest date, then lowest id). Count every order, whatever the status. The first order itself shows 0.
- Salary quartilesSplit the employees into four groups of as equal size as possible by salary, highest salaries in group 1. Return each employee's name and their group number.
- 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.
- 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.
Interview classics
- 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.
- Salary against the department averageFor every employee who has a department, return the name and the difference between their salary and the average salary of their department, rounded to 2 decimals. Above the average is positive, below is negative.
- 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.
- 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.
- First order not paidReturn the names of customers whose first order (earliest date, then lowest id) has a status other than paid.
- 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.
- 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.
- 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.
- 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.
- Refund review, step 3: who gets the refundsIs it a few customers? For every customer with at least one refunded order, return the name, the number of refunded orders, the refunded amount and that customer's share of the total refunded amount in percent, rounded to 1 decimal.
- Payroll review, step 4: hires per year and running headcountHow did the team grow? For every year in which someone was hired, return the year as a number, the number of hires in that year and the running total of hires up to and including that year.
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.