SQL window functions: ROW_NUMBER, RANK, DENSE_RANK and running totals
A window function calculates across a set of rows related to the current row without collapsing them into one, the way GROUP BY does. They are a favourite in data analyst interviews: ranking, top N per group and running totals.
What is the difference between the ranking functions?
Sales of 500, 400, 400 and 300:
| amount | ROW_NUMBER | RANK | DENSE_RANK |
|---|---|---|---|
| 500 | 1 | 1 | 1 |
| 400 | 2 | 2 | 2 |
| 400 | 3 | 2 | 2 |
| 300 | 4 | 4 | 3 |
ROW_NUMBER never ties. RANK skips a number after a tie, DENSE_RANK doesn't.
How do you get the top 3 per group?
SELECT * FROM ( SELECT region, name, amount, ROW_NUMBER() OVER (PARTITION BY region ORDER BY amount DESC) AS rn FROM sales) tWHERE rn <= 3;
PARTITION BY restarts the numbering for each region. You can't filter a window function in WHERE of the same query, hence the subquery.
How do you calculate a running total?
SELECT order_date, amount, SUM(amount) OVER (ORDER BY order_date) AS running_totalFROM orders;
Other useful ones
LAG and LEAD read the previous or next row, which is handy for month-over-month change: amount - LAG(amount) OVER (ORDER BY month).
Practise window functions
Updated November 2026.