SQL Window Functions Explained: RANK, DENSE_RANK, ROW_NUMBER and More

8 min read

A window function calculates a value across a set of rows related to the current row, and returns that value on every row instead of collapsing the rows into one. That is the whole difference from GROUP BY: SUM with GROUP BY gives you one row per group, while SUM() OVER (PARTITION BY region) keeps every row and adds the region total beside it. Ranking, running totals, month-on-month change and moving averages are all window functions.

They are also the topic that separates a fresher SQL interview from a mid-level one. If you can explain why RANK skips a number and DENSE_RANK does not, and write a top-N-per-group query without looking anything up, you are ahead of most candidates.

The anatomy of a window function

Every window function has the same shape: a function, the keyword OVER, and inside the brackets up to three optional parts that define the window.

Part What it does Syntax Example
Function The calculation to run function_name(column) SUM(revenue)
OVER Marks it as a window function function OVER (…) SUM(revenue) OVER ()
PARTITION BY Splits rows into groups; the function restarts in each PARTITION BY column PARTITION BY region
ORDER BY Sets the order inside each partition ORDER BY column ORDER BY revenue DESC
Frame Limits which rows around the current one are used ROWS BETWEEN start AND end ROWS BETWEEN 2 PRECEDING AND CURRENT ROW

An empty OVER () means the window is the entire result. PARTITION BY without ORDER BY gives you a group total on every row. ORDER BY without PARTITION BY ranks or accumulates across the whole table.

The window functions you will actually use

The table below lists the functions that turn up in analyst work and interviews, grouped by what they do.

Function Family What it returns Example
ROW_NUMBER() Ranking 1, 2, 3, 4 with no ties, ever ROW_NUMBER() OVER (ORDER BY revenue DESC)
RANK() Ranking Ties share a rank, then the next rank is skipped (1, 2, 2, 4) RANK() OVER (ORDER BY revenue DESC)
DENSE_RANK() Ranking Ties share a rank, no gap after (1, 2, 2, 3) DENSE_RANK() OVER (ORDER BY revenue DESC)
NTILE(n) Ranking Splits rows into n roughly equal buckets NTILE(4) OVER (ORDER BY revenue DESC)
SUM, AVG, COUNT, MIN, MAX Aggregate The aggregate over the window, on every row SUM(revenue) OVER (PARTITION BY region)
LAG(col, n) Offset The value n rows before the current one LAG(revenue) OVER (ORDER BY month)
LEAD(col, n) Offset The value n rows after the current one LEAD(revenue) OVER (ORDER BY month)
FIRST_VALUE(col) Offset The first value in the window FIRST_VALUE(rep_name) OVER (PARTITION BY region ORDER BY revenue DESC)

The data used throughout

The examples follow one scenario: a Bengaluru D2C skincare brand with seven sales reps across two regions. This is their October revenue, in rupees.

rep_name region revenue
Asha North 420000
Bhavesh North 380000
Chitra North 380000
Deepak North 310000
Farah South 510000
Gopal South 460000
Harini South 460000

There are two deliberate ties: Bhavesh and Chitra at 3,80,000, and Gopal and Harini at 4,60,000. Ties are where the three ranking functions stop agreeing.

RANK vs DENSE_RANK vs ROW_NUMBER

This is the single most asked window-function question, so here are all three side by side on the same ordering.

Query: SELECT rep_name, revenue, ROW_NUMBER() OVER (ORDER BY revenue DESC, rep_name) AS row_num, RANK() OVER (ORDER BY revenue DESC) AS rnk, DENSE_RANK() OVER (ORDER BY revenue DESC) AS dense_rnk FROM rep_sales

rep_name revenue row_num rnk dense_rnk
Farah 510000 1 1 1
Gopal 460000 2 2 2
Harini 460000 3 2 2
Asha 420000 4 4 3
Bhavesh 380000 5 5 4
Chitra 380000 6 5 4
Deepak 310000 7 7 5

Read the Asha row. ROW_NUMBER gives her 4 because she is the fourth row. RANK also gives her 4, because two people tied at rank 2 and RANK leaves a gap for them, so rank 3 does not exist. DENSE_RANK gives her 3, because it never leaves gaps: she has the third-highest distinct revenue.

How to choose:

  • ROW_NUMBER when you need exactly one row per position, for example picking the single latest order per customer. Add a tie-breaker column to the ORDER BY (rep_name above), or the database is free to number tied rows in any order and your result can change between runs.
  • RANK when the gap carries meaning, as in a sports table: if two people tie for second, nobody came third.
  • DENSE_RANK when you want the Nth highest distinct value, which is the classic “find the second highest salary” interview question. DENSE_RANK equal to 2 answers it correctly even when the top salary is shared.

PARTITION BY: ranking inside each group

Add PARTITION BY and the ranking restarts for every region. Combined with a CTE, this gives you the top-N-per-group query that every analyst writes weekly.

Query, in two parts. First: WITH ranked AS (SELECT rep_name, region, revenue, DENSE_RANK() OVER (PARTITION BY region ORDER BY revenue DESC) AS region_rank FROM rep_sales). Then: SELECT rep_name, region, revenue, region_rank FROM ranked WHERE region_rank <= 2

rep_name region revenue region_rank
Asha North 420000 1
Bhavesh North 380000 2
Chitra North 380000 2
Farah South 510000 1
Gopal South 460000 2
Harini South 460000 2

You asked for the top two per region and got three in each, because of the ties. That is correct behaviour for DENSE_RANK and RANK. If the business wants exactly two names per region, switch to ROW_NUMBER and decide the tie-breaker deliberately, for example the rep with more orders wins.

Why the CTE? Because you cannot filter on a window function in the WHERE clause of the same query. The database computes window functions after WHERE has already run, so WHERE region_rank <= 2 fails with an error saying the column does not exist or that window functions are not allowed there. Wrap the ranking in a CTE or subquery and filter outside it. Snowflake, BigQuery and Databricks offer a QUALIFY clause that filters window results directly; MySQL, PostgreSQL and SQL Server do not.

Aggregate window functions: a total on every row

An aggregate with OVER keeps every row and attaches the aggregate to it. That makes “what share of the region did each rep bring in” a one-step query.

Query: SELECT rep_name, region, revenue, SUM(revenue) OVER (PARTITION BY region) AS region_total, ROUND(100.0 * revenue / SUM(revenue) OVER (PARTITION BY region), 1) AS pct_of_region FROM rep_sales

rep_name region revenue region_total pct_of_region
Asha North 420000 1490000 28.2
Bhavesh North 380000 1490000 25.5
Chitra North 380000 1490000 25.5
Deepak North 310000 1490000 20.8
Farah South 510000 1430000 35.7
Gopal South 460000 1430000 32.2
Harini South 460000 1430000 32.2

With GROUP BY region you would get two rows and lose the reps. To get this without a window function you would need a subquery joined back to the table, which is longer and easier to get wrong. Note the 100.0 rather than 100: in SQL Server and PostgreSQL, an integer divided by an integer is an integer, and every percentage would come out as 0.

Running totals, LAG and moving averages

The second big use of window functions is time series. Here is the brand’s monthly revenue for four months.

month revenue
2026-07 1240000
2026-08 1310000
2026-09 1185000
2026-10 1460000

One query gives a running total, the previous month’s figure, the change, and a three-month moving average. Each clause is on its own row so you can read it:

Column Expression
running_total SUM(revenue) OVER (ORDER BY month ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
prev_month LAG(revenue) OVER (ORDER BY month)
change revenue – LAG(revenue) OVER (ORDER BY month)
moving_avg_3m AVG(revenue) OVER (ORDER BY month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
month revenue running_total prev_month change moving_avg_3m
2026-07 1240000 1240000 NULL NULL 1240000
2026-08 1310000 2550000 1240000 70000 1275000
2026-09 1185000 3735000 1310000 -125000 1245000
2026-10 1460000 5195000 1185000 275000 1318333

LAG returns NULL for July because there is no earlier row. If you want 0 instead, LAG takes a default as its third argument: LAG(revenue, 1, 0). The moving average for July and August is built from fewer than three months because there are not three months yet; decide whether to show those rows or filter them out before you put the number on a dashboard.

LEAD is the same as LAG in the other direction. It is useful for “days until the customer’s next order” when you order by order_date within PARTITION BY customer_id.

The frame clause, and the running-total trap

The frame decides which rows the function sees. You can skip it most of the time, but the default is the cause of a well-known bug.

Frame Rows used Typical use
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW Everything from the first row up to this one Running total
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW This row and the two before Three-period moving average
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING The whole partition LAST_VALUE that actually returns the last value
RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW Up to this row, including every row tied with it The default when ORDER BY is present

The trap: if you write SUM(revenue) OVER (ORDER BY revenue) with no frame, the default is RANGE, not ROWS. RANGE treats tied rows as one step, so Bhavesh and Chitra, both at 3,80,000, would show the same running total, including each other’s revenue. A daily running total ordered by order_date has the same problem whenever two orders share a date. Write ROWS explicitly whenever you mean row by row.

The same default explains why LAST_VALUE so often returns the current row’s value instead of the last one. With ORDER BY and the default frame, the window ends at the current row. Give it ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING, or use FIRST_VALUE with the order reversed.

Where MySQL, PostgreSQL and SQL Server differ

Window functions are standard SQL and the syntax above runs on all three, with a few differences worth knowing before an interview or a migration.

Point MySQL PostgreSQL SQL Server
Support From version 8.0; MySQL 5.7 has none Since 8.4 Ranking since 2005; full frames since 2012
QUALIFY to filter ranks No No No
Integer division in pct Returns a decimal Truncates to integer Truncates to integer
Named windows (WINDOW w AS …) Yes Yes From SQL Server 2022
FILTER clause on aggregates No Yes No

The MySQL version point matters in India more than you would expect. Plenty of company databases and shared hosting setups still run 5.7, and on those the queries in this article fail outright. The workaround there is a self-join or a correlated subquery, which is exactly why window functions were added.

Mistakes that produce wrong answers

Using ROW_NUMBER without a tie-breaker. Two rows with the same value get numbers 2 and 3 in an order the database chooses, and that order can change. Your “latest order per customer” picks a different order next week.

Filtering the rank in WHERE. It errors in MySQL, PostgreSQL and SQL Server. Rank in a CTE, filter outside.

Forgetting PARTITION BY. A rank that should restart per city runs across the whole country instead, and every city after the first starts at some number other than 1.

Trusting the default frame for running totals. RANGE groups ties together. Use ROWS.

Reaching for GROUP BY when you need the detail rows. If the answer needs both the individual row and its group’s total, that is a window function, not GROUP BY and a join back.

Window functions build directly on aggregates and on GROUP BY, so if PARTITION BY still feels slippery, get comfortable with grouping first. Joins come up constantly alongside them; our guide to SQL joins uses the same style of worked examples. For how these questions are framed in hiring rounds, see the advanced section of our SQL interview questions.

Frequently asked questions

What is a window function in SQL?

A window function performs a calculation across a set of rows that are related to the current row, and returns the result on every row rather than collapsing them. It is written with the OVER clause, for example SUM(revenue) OVER (PARTITION BY region). Ranking, running totals, moving averages and comparisons with the previous row are all done with window functions.

What is the difference between RANK and DENSE_RANK?

Both give tied rows the same rank. RANK then skips the following numbers, so a tie for second place is followed by fourth. DENSE_RANK does not skip, so the next row is third. Use DENSE_RANK when you want the Nth highest distinct value, such as the second highest salary.

What is the difference between ROW_NUMBER and RANK?

ROW_NUMBER gives every row a unique number even when values tie, so two equal salaries get 1 and 2. RANK gives tied rows the same number. Use ROW_NUMBER when you need exactly one row per position, such as removing duplicates or picking the latest record per customer, and always add a tie-breaker to its ORDER BY.

What is the difference between GROUP BY and PARTITION BY?

GROUP BY collapses rows, returning one row per group. PARTITION BY, used inside a window function, divides rows into groups for the calculation but keeps every original row in the result. If you need each order alongside its customer’s total, use PARTITION BY.

Can I use a window function in the WHERE clause?

No. Window functions are evaluated after WHERE, GROUP BY and HAVING, so the value does not exist yet when WHERE runs. Compute the window function inside a CTE or subquery, then filter on it in the outer query. Some cloud warehouses such as Snowflake and BigQuery provide QUALIFY for this, but MySQL, PostgreSQL and SQL Server do not.

Does MySQL support window functions?

Yes, from MySQL 8.0 onwards. MySQL 5.7 and earlier have no window functions, so ROW_NUMBER, RANK and the OVER clause all fail there. Check your version with SELECT VERSION() before debugging a query that looks correct.

Practise window functions on real data

Window functions read easily and go wrong quietly, through a missing tie-breaker or a default frame nobody noticed. The way to get them right is to write a lot of them against real tables and have someone point out why a running total is off by a tied row.

SkilloVilla’s SQL: Beginner to Advanced course goes from the fundamental statements through aggregation, joins and advanced SQL statements, taught in live classes with mentor support and practice on SQL playgrounds. If you want SQL as part of a full analyst path with Python and placement support, look at the Data Analytics with Python track.

Primary Key, Foreign Key and Constraints in SQL, With…

Primary key and foreign key in SQL explained with examples: how they link tables, composite keys, ON DELETE CASCADE, and UNIQUE, CHECK and NOT...
SkilloVilla Team
6 min read

GROUP BY and HAVING in SQL, With Examples

GROUP BY in SQL explained with examples: grouping by one or more columns, HAVING vs WHERE, the order SQL runs a query in, and...
SkilloVilla Team
6 min read

CTE in SQL: The WITH Clause Explained With Examples

CTE in SQL explained: what a common table expression is, WITH clause syntax, chained CTEs, recursive CTEs, and CTE vs subquery, with worked examples.
SkilloVilla Team
6 min read

Leave a Reply