---
title: SQL Window Functions: ROW_NUMBER, RANK, LAG, Running Total
url: https://www.masaischool.com/resources/sql-window-functions-explained
description: SQL window functions with executed examples: ROW_NUMBER vs RANK vs DENSE_RANK, top N per group, LAG and LEAD, running total, moving average, gaps and islands.
updated: 2026-12-01
publisher: Masai (https://www.masaischool.com)
---

# SQL window functions explained: ROW_NUMBER, RANK, LAG, running totals and more

> **Short answer**
>
> A window function calculates a value for each row using a set of related rows, without collapsing them like GROUP BY does. You write it as function() OVER (PARTITION BY group ORDER BY column). Common ones are ROW_NUMBER, RANK, DENSE_RANK for ranking, LAG and LEAD for neighbouring rows, and SUM or AVG for running totals and moving averages.

Window functions are the SQL topic that separates a candidate who can query from one who can analyse. This page works through the five patterns that cover most interview and dashboard needs: ranking with ties, top N per group, LAG and LEAD for change over time, running totals and moving averages, and gaps and islands. Every query was executed and the output quoted is what it printed.

SQLite added window functions in version 3.25.0 (released 15 September 2018, according to [SQLite's window function documentation](https://www.sqlite.org/windowfunctions.html)), so any current Python has them; the scripts print sqlite3.sqlite_version on the first line. The syntax is the same in PostgreSQL and in MySQL 8 and later ([MySQL 8.4 window functions](https://dev.mysql.com/doc/refman/8.4/en/window-functions.html)). For the wider interview set, see [SQL interview questions](https://www.masaischool.com/resources/sql-interview-questions), and for grouping basics see [SQL joins explained](https://www.masaischool.com/resources/sql-joins-explained-with-examples).

## Window function vs GROUP BY, and the syntax in one table

GROUP BY returns one row per group. A window function keeps every row and adds a column computed over a "window" of related rows. The window has three parts, all inside OVER (...).

| Part | Keyword | What it does | If you omit it |
|---|---|---|---|
| Which rows are related | PARTITION BY dept | Restarts the calculation for each group | One window over the whole result |
| Order inside the window | ORDER BY salary DESC | Defines ranking order and running direction | No order: all rows are peers |
| Which rows to include | ROWS BETWEEN 2 PRECEDING AND CURRENT ROW | The frame, relative to the current row | With ORDER BY: start of partition to current row, including ties |

The rule people forget: you cannot use a window function in WHERE, because windows are computed after filtering. To filter on a rank, compute it in a subquery or CTE (common table expression) and filter outside. Some databases offer QUALIFY to skip that step, but SQLite, PostgreSQL and MySQL do not, so the pattern below is the portable one.

## ROW_NUMBER, RANK and DENSE_RANK: how ties behave

All three number rows within a partition. They differ only when two rows tie on the ORDER BY value. The data has seven employees in two departments, with ties at 100 in Engineering and at 90 in Sales. WINDOW w AS (...) names the window once so the three functions share it.import sqlite3 print("SQLite", sqlite3.sqlite_version) # window functions need 3.25.0 or newer db = sqlite3.connect(":memory:") db.executescript(""" CREATE TABLE emp (name TEXT, dept TEXT, salary INTEGER); INSERT INTO emp VALUES ('Asha','Eng',120),('Ravi','Eng',100),('Meera','Eng',100),('Karan','Eng',80), ('Neha','Sales',90),('Dev','Sales',90),('Isha','Sales',70); """) def show(title, sql): print("--", title) for row in db.execute(sql): print(" ", row) show("ROW_NUMBER vs RANK vs DENSE_RANK (ties on 100 and 90)", """ SELECT name, dept, salary, ROW_NUMBER() OVER w AS row_number, RANK() OVER w AS rank, DENSE_RANK() OVER w AS dense_rank FROM emp WINDOW w AS (PARTITION BY dept ORDER BY salary DESC) ORDER BY dept, salary DESC, name""") show("Window next to GROUP BY: each salary against the department average", """ SELECT name, dept, salary, ROUND(AVG(salary) OVER (PARTITION BY dept), 1) AS dept_avg, ROUND(salary - AVG(salary) OVER (PARTITION BY dept), 1) AS vs_avg FROM emp ORDER BY dept, name""") show("Top 2 salaries per department with DENSE_RANK (ties kept)", """ SELECT dept, name, salary FROM ( SELECT *, DENSE_RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS r FROM emp) WHERE r <= 2 ORDER BY dept, salary DESC, name""") show("Top 2 per department with ROW_NUMBER (exactly 2 rows each)", """ SELECT dept, name, salary FROM ( SELECT *, ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC, name) AS r FROM emp) WHERE r <= 2 ORDER BY dept, r""")SQLite 3.54.0 -- ROW_NUMBER vs RANK vs DENSE_RANK (ties on 100 and 90) ('Asha', 'Eng', 120, 1, 1, 1) ('Meera', 'Eng', 100, 3, 2, 2) ('Ravi', 'Eng', 100, 2, 2, 2) ('Karan', 'Eng', 80, 4, 4, 3) ('Dev', 'Sales', 90, 2, 1, 1) ('Neha', 'Sales', 90, 1, 1, 1) ('Isha', 'Sales', 70, 3, 3, 2) -- Window next to GROUP BY: each salary against the department average ('Asha', 'Eng', 120, 100.0, 20.0) ('Karan', 'Eng', 80, 100.0, -20.0) ('Meera', 'Eng', 100, 100.0, 0.0) ('Ravi', 'Eng', 100, 100.0, 0.0) ('Dev', 'Sales', 90, 83.3, 6.7) ('Isha', 'Sales', 70, 83.3, -13.3) ('Neha', 'Sales', 90, 83.3, 6.7) -- Top 2 salaries per department with DENSE_RANK (ties kept) ('Eng', 'Asha', 120) ('Eng', 'Meera', 100) ('Eng', 'Ravi', 100) ('Sales', 'Dev', 90) ('Sales', 'Neha', 90) ('Sales', 'Isha', 70) -- Top 2 per department with ROW_NUMBER (exactly 2 rows each) ('Eng', 'Asha', 120) ('Eng', 'Meera', 100) ('Sales', 'Dev', 90) ('Sales', 'Neha', 90)

| Function | On a tie | Next rank after the tie | Use it for |
|---|---|---|---|
| ROW_NUMBER | Unique numbers; the tied order is arbitrary unless you add a tiebreaker | Continues 1, 2, 3, 4 | Exactly N rows, deduplication |
| RANK | Same number for ties | Skips: 1, 2, 2, 4 | Competition style ranking |
| DENSE_RANK | Same number for ties | No gap: 1, 2, 2, 3 | Top N distinct values, "second highest salary" |

Look at Engineering: Meera and Ravi both earn 100. RANK gives them 2 and 2, then Karan gets 4. DENSE_RANK gives 2 and 2, then 3. ROW_NUMBER gave Ravi 2 and Meera 3, but that order between tied rows is not guaranteed, so add a second sort key such as name when you need a repeatable result.

### Top N per group

The last two queries in the script above show the portable pattern: rank inside a subquery, filter outside. The choice of function changes the answer. DENSE_RANK with <= 2 returned three Engineering rows and three Sales rows because ties are kept; ROW_NUMBER with <= 2 returned exactly two rows each and dropped Ravi and Isha, whom DENSE_RANK kept. Say which behaviour the question wants before you write the query. The plain aggregate comparison in the second query, salary against department average, is something GROUP BY alone cannot do without joining back to itself.

## LAG and LEAD: compare a row with its neighbours

LAG(col) reads the previous row in the window order and LEAD(col) reads the next. Both accept an offset and a default: LAG(revenue, 1, 0). The first row has no previous row, so you get NULL unless you supply a default. This is the standard way to compute month-over-month change.import sqlite3 db = sqlite3.connect(":memory:") db.executescript(""" CREATE TABLE monthly (month TEXT PRIMARY KEY, revenue INTEGER); INSERT INTO monthly VALUES ('2026-01',100),('2026-02',120),('2026-03',90),('2026-04',150),('2026-05',150),('2026-06',200); """) def show(title, sql): print("--", title) for row in db.execute(sql): print(" ", row) show("LAG and LEAD with month-over-month change", """ SELECT month, revenue, LAG(revenue) OVER (ORDER BY month) AS prev, LEAD(revenue) OVER (ORDER BY month) AS next, revenue - LAG(revenue) OVER (ORDER BY month) AS change, ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month)) / LAG(revenue) OVER (ORDER BY month), 1) AS pct FROM monthly""") show("Running total (explicit ROWS frame)", """ SELECT month, revenue, SUM(revenue) OVER (ORDER BY month ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total FROM monthly""") show("3-month moving average (partial window at the start)", """ SELECT month, revenue, ROUND(AVG(revenue) OVER (ORDER BY month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 1) AS ma3, COUNT(*) OVER (ORDER BY month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS rows_in_window FROM monthly""") show("Default frame trap: ties share a running total (RANGE) vs ROWS", """ SELECT month, revenue, SUM(revenue) OVER (ORDER BY revenue) AS default_frame, SUM(revenue) OVER (ORDER BY revenue, month ROWS UNBOUNDED PRECEDING) AS rows_frame FROM monthly ORDER BY revenue, month""")-- LAG and LEAD with month-over-month change ('2026-01', 100, None, 120, None, None) ('2026-02', 120, 100, 90, 20, 20.0) ('2026-03', 90, 120, 150, -30, -25.0) ('2026-04', 150, 90, 150, 60, 66.7) ('2026-05', 150, 150, 200, 0, 0.0) ('2026-06', 200, 150, None, 50, 33.3) -- Running total (explicit ROWS frame) ('2026-01', 100, 100) ('2026-02', 120, 220) ('2026-03', 90, 310) ('2026-04', 150, 460) ('2026-05', 150, 610) ('2026-06', 200, 810) -- 3-month moving average (partial window at the start) ('2026-01', 100, 100.0, 1) ('2026-02', 120, 110.0, 2) ('2026-03', 90, 103.3, 3) ('2026-04', 150, 120.0, 3) ('2026-05', 150, 130.0, 3) ('2026-06', 200, 166.7, 3) -- Default frame trap: ties share a running total (RANGE) vs ROWS ('2026-03', 90, 90, 90) ('2026-01', 100, 190, 190) ('2026-02', 120, 310, 310) ('2026-04', 150, 610, 460) ('2026-05', 150, 610, 610) ('2026-06', 200, 810, 810)

The first block shows March falling 25.0 percent from February and April rising 66.7 percent. Guard the percentage against a zero previous value in real data, for example with NULLIF(LAG(revenue) OVER (...), 0). The window ordering uses month text in YYYY-MM form, which sorts correctly as text; with other date formats convert first.

## Running totals and moving averages: the frame matters

A running total is SUM(x) OVER (ORDER BY ...). A moving average narrows the frame to the last few rows. The output above shows both: the cumulative revenue reaches 810 by June, and the 3-month average starts with fewer rows (the rows_in_window column shows 1, 2 and then 3), so the first two averages are partial.

The last block exposes the most common trap. With ORDER BY and no frame, the default is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which treats rows with equal sort values as peers. April and May both have revenue 150, so the default column shows 610 on both rows, while the explicit ROWS frame gives 460 then 610. Pick ROWS for a running total by row, and keep RANGE only when you want ties to share a value. Frames work the same way in SQLite, PostgreSQL and MySQL.

| Goal | Frame to write |
|---|---|
| Running total by row | ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW |
| Moving average of the last 3 rows | ROWS BETWEEN 2 PRECEDING AND CURRENT ROW |
| Centred 3-point average | ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING |
| Whole-partition total on every row | SUM(x) OVER (PARTITION BY g) with no ORDER BY |

## Gaps and islands: find streaks with ROW_NUMBER

"Longest login streak" and "consecutive days of activity" are gaps-and-islands problems: find unbroken runs in a sequence. The trick is that within one unbroken run, the date minus the row number is constant. When a day is skipped, the difference jumps, and that constant becomes a group label.import sqlite3 db = sqlite3.connect(":memory:") db.executescript(""" CREATE TABLE logins (user TEXT, day TEXT); INSERT INTO logins VALUES ('asha','2026-11-01'),('asha','2026-11-02'),('asha','2026-11-03'), ('asha','2026-11-06'),('asha','2026-11-07'),('asha','2026-11-10'); """) rows = db.execute(""" WITH numbered AS ( SELECT user, day, julianday(day) - ROW_NUMBER() OVER (PARTITION BY user ORDER BY day) AS grp FROM logins) SELECT user, MIN(day) AS streak_start, MAX(day) AS streak_end, COUNT(*) AS days FROM numbered GROUP BY user, grp ORDER BY streak_start""").fetchall() for r in rows: print(r)('asha', '2026-11-01', '2026-11-03', 3) ('asha', '2026-11-06', '2026-11-07', 2) ('asha', '2026-11-10', '2026-11-10', 1)

The three groups are the islands: 1 to 3 November, 6 to 7 November and 10 November alone. julianday(day) converts a date to a number in SQLite; in PostgreSQL you would subtract an interval (day - ROW_NUMBER() OVER (...) * INTERVAL '1 day'), and in MySQL use DATE_SUB. If a user can log in twice a day, deduplicate by day first, or the row numbers will drift.

Next steps: add these patterns to a portfolio query set using [free data analytics tools](https://www.masaischool.com/resources/tools/free-data-analytics-tools), and test yourself with the window questions in [SQL interview questions](https://www.masaischool.com/resources/sql-interview-questions). Analysts can see where these fit in the [data analytics path](https://www.masaischool.com/resources/data-analytics).

## Frequently asked questions

### What are window functions in SQL?

Window functions compute a value for each row from a set of related rows, called the window, and keep every row in the output. Unlike GROUP BY they do not collapse rows. They use the OVER clause with optional PARTITION BY, ORDER BY and a frame. Typical uses are ranking, running totals, moving averages and comparing a row with the previous one.

### What is the difference between RANK, DENSE_RANK and ROW_NUMBER?

All three number rows in order. ROW_NUMBER gives a unique number even for ties. RANK gives tied rows the same number and then skips (1, 2, 2, 4). DENSE_RANK gives tied rows the same number with no gap (1, 2, 2, 3). Use DENSE_RANK for second-highest salary questions.

### How do you get the top N rows per group in SQL?

Rank rows with ROW_NUMBER, RANK or DENSE_RANK using PARTITION BY the group, put that query in a subquery or CTE, and filter the rank column in the outer query. You cannot filter on a window function in the same SELECT. Choose ROW_NUMBER for exactly N rows or DENSE_RANK to keep ties.

### How do you calculate a running total in SQL?

Use SUM(column) OVER (ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW). Add PARTITION BY to restart per customer or category. Write the ROWS frame explicitly, because the default RANGE frame gives tied rows the same total, which surprises people when two rows share a date.

### What do LAG and LEAD do?

LAG returns a value from an earlier row in the window order and LEAD from a later row, by default one row away. They return NULL when no such row exists unless you pass a default. They replace self joins for month-over-month change, time between events and next or previous value comparisons.

### Can I use window functions in WHERE or GROUP BY?

Not directly. Window functions are evaluated after WHERE, GROUP BY and HAVING, so they only appear in SELECT and ORDER BY. To filter on one, compute it in a subquery or CTE and filter in the outer query. Some other databases add a QUALIFY clause for this, but it is not part of SQLite, MySQL or standard PostgreSQL.

### Which databases support window functions?

PostgreSQL, SQL Server, Oracle, current MySQL (documented in the 8.4 manual) and SQLite from version 3.25.0 all do. Syntax for the common functions is nearly identical, so a query that runs in SQLite usually runs elsewhere. Date arithmetic differs, as the gaps-and-islands section shows.
