DBMS & SQL · Pro · Topic 4 of 5
SQL: Window Functions
6 questions.
Your progress0%
- 1st Visit
- 0/6
- 2nd Visit
- 0/6
- Revise
- 0/6
Overview
A window function computes a value for each row from a set of related rows, without collapsing the rows the way GROUP BY does. The OVER clause defines the window: PARTITION BY splits the rows into groups, ORDER BY orders the rows inside each group, and an optional frame such as ROWS BETWEEN 2 PRECEDING AND CURRENT ROW limits which rows are included. Ranking functions (ROW_NUMBER, RANK, DENSE_RANK), offset functions (LAG, LEAD) and running aggregates (SUM(...) OVER) solve most interview problems. Look for "top n per group", "previous day", "running total" or "moving average". MySQL supports window functions from version 8.0.
SELECT day, amount,
SUM(amount) OVER (ORDER BY day) AS running_total,
LAG(amount) OVER (ORDER BY day) AS prev_amount
FROM daily_sales;
Questions
| # | Problem | Platform | Difficulty | Open | 1st1st Visit | 2nd2nd Visit | RevRevise |
|---|---|---|---|---|---|---|---|
| 1 | What is the difference between ROW_NUMBER, RANK and DENSE_RANK? | Concept | Easy | Read the answer to What is the difference between ROW_NUMBER, RANK and DENSE_RANK? | |||
| 2 | Rank Scores | LeetCode | Medium | Solve Rank Scores on LeetCode (opens in a new tab) | |||
| 3 | Consecutive Numbers | LeetCode | Medium | Solve Consecutive Numbers on LeetCode (opens in a new tab) | |||
| 4 | Last Person to Fit in the Bus | LeetCode | Medium | Solve Last Person to Fit in the Bus on LeetCode (opens in a new tab) | |||
| 5 | Restaurant Growth | LeetCode | Medium | Solve Restaurant Growth on LeetCode (opens in a new tab) | |||
| 6 | Department Top Three Salaries | LeetCode | Hard | Solve Department Top Three Salaries on LeetCode (opens in a new tab) |