AnalystPracticeGuides
DashboardSign up

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.

Watch it solved. Q9: top earner per department (RANK), from 5:53, in our video “SQL Interview Questions and Answers for Data Analysts (Easy to Hard)”. Pressing play loads the video from YouTube (privacy). Open on YouTube

What is the difference between the ranking functions?

Sales of 500, 400, 400 and 300:

amountROW_NUMBERRANKDENSE_RANK
500111
400222
400322
300443

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
) t
WHERE 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_total
FROM 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).

Try it yourself. Practise this in a real database in your browser, with instant feedback.
Practise window functions

Updated November 2026.

← All free guides