Running totals, rankings, top N per group, LAG and LEAD, and moving averages, explained with one small table and queries tested on PostgreSQL, MySQL, SQLite and DuckDB.

By Michael Stromberg, Hack Reactor graduate (2016) · Last verified November 30, 2026
Window functions are the SQL feature that separates beginners from people who can actually answer business questions with data. Running totals, rankings, “top 3 per category,” month-over-month change, and moving averages are all one short query once you know them, and they come up constantly in data analyst work and SQL interviews.
This tutorial explains how window functions work using one small table, with every query tested on PostgreSQL, MySQL, SQLite, and DuckDB. Each example shows the real result, so you can check your work as you go.
The short answer: a window function calculates a value for each row using a group of related rows, called its window, without collapsing those rows into one the way GROUP BY does. You write it as a function followed by OVER (…), and the OVER clause says which rows are in the window.

What you need
You need a database that supports window functions. All the major ones do: PostgreSQL, MySQL 8.0 and later, SQLite 3.25 and later, SQL Server, Oracle, and cloud warehouses such as BigQuery and Snowflake. If you don’t have one installed, the quickest option is a free online playground such as DB Fiddle: paste the table below into the left-hand Schema SQL box, put each query in the Query SQL box, and click Run. On a Mac, sqlite3 is already installed and works too.
You should already know SELECT, WHERE, GROUP BY, and ORDER BY. Every example uses this table of monthly revenue for two sales regions:
CREATE TABLE sales (
month CHAR(7) NOT NULL,
region VARCHAR(10) NOT NULL,
revenue INTEGER NOT NULL
);
INSERT INTO sales (month, region, revenue) VALUES
('2026-01', 'East', 4200), ('2026-01', 'West', 3100),
('2026-02', 'East', 3900), ('2026-02', 'West', 3600),
('2026-03', 'East', 5100), ('2026-03', 'West', 3600),
('2026-04', 'East', 4800), ('2026-04', 'West', 4400),
('2026-05', 'East', 5600), ('2026-05', 'West', 4100),
('2026-06', 'East', 6100), ('2026-06', 'West', 5000);Twelve rows: six months for the East region and six for the West. Notice that the West made exactly $3,600 in both February and March. That tie matters later, when we rank months.
GROUP BY vs. window functions
Say you want each region’s total revenue. With GROUP BY, you get one row per region:
SELECT region, SUM(revenue) AS total FROM sales GROUP BY region ORDER BY region;
Result:
region | total |
|---|---|
| East | 29700 |
| West | 23800 |
That’s fine for a summary, but the individual months are gone. Now suppose you want to see each month next to its region’s total, so you can compare them. That’s exactly what a window function does:
SELECT month, region, revenue,
SUM(revenue) OVER (PARTITION BY region) AS region_total
FROM sales
ORDER BY region, month;Result:
month | region | revenue | region_total |
|---|---|---|---|
| 2026-01 | East | 4200 | 29700 |
| 2026-02 | East | 3900 | 29700 |
| 2026-03 | East | 5100 | 29700 |
| 2026-04 | East | 4800 | 29700 |
| 2026-05 | East | 5600 | 29700 |
| 2026-06 | East | 6100 | 29700 |
| 2026-01 | West | 3100 | 23800 |
| 2026-02 | West | 3600 | 23800 |
| 2026-03 | West | 3600 | 23800 |
| 2026-04 | West | 4400 | 23800 |
| 2026-05 | West | 4100 | 23800 |
| 2026-06 | West | 5000 | 23800 |
Same SUM, but followed by OVER (PARTITION BY region), and now all 12 rows survive. Each row gets the total of the rows in its partition, meaning the rows with the same region. That’s the core idea of window functions: calculate across rows, but keep every row.
How the OVER clause works
Everything about a window function is controlled by what goes inside the parentheses after OVER. There are three optional parts, always in this order:

PARTITION BYsplits the rows into groups. The function starts over for each group. Leave it out and the whole result is one big window:SUM(revenue) OVER ()is the grand total on every row.ORDER BYsorts the rows inside each partition. It’s required for ranking functions and forLAGandLEAD, and it turns a total into a running total.- The frame, such as
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW, narrows the window to a range of rows around the current one. It’s how you build moving averages.
Window functions come in three families. Aggregate functions you already know (SUM, AVG, COUNT, MIN, MAX) become window functions when you add OVER. Ranking functions (ROW_NUMBER, RANK, DENSE_RANK, NTILE) number the rows. Offset functions (LAG, LEAD, FIRST_VALUE, LAST_VALUE) read a value from another row. The rest of this tutorial covers the patterns you’ll use most.
1. Percent of total
Because the window total sits on every row, dividing by it gives each month’s share of its region’s revenue:
SELECT month, region, revenue,
ROUND(100.0 * revenue / SUM(revenue) OVER (PARTITION BY region), 1) AS pct_of_region
FROM sales
ORDER BY region, month;Result:
month | region | revenue | pct_of_region |
|---|---|---|---|
| 2026-01 | East | 4200 | 14.1 |
| 2026-02 | East | 3900 | 13.1 |
| 2026-03 | East | 5100 | 17.2 |
| 2026-04 | East | 4800 | 16.2 |
| 2026-05 | East | 5600 | 18.9 |
| 2026-06 | East | 6100 | 20.5 |
| 2026-01 | West | 3100 | 13.0 |
| 2026-02 | West | 3600 | 15.1 |
| 2026-03 | West | 3600 | 15.1 |
| 2026-04 | West | 4400 | 18.5 |
| 2026-05 | West | 4100 | 17.2 |
| 2026-06 | West | 5000 | 21.0 |
The 100.0 matters. In PostgreSQL, SQL Server, and SQLite, dividing one whole number by another throws away the decimals, so 100 * 4200 / 29700 would give 14 instead of 14.1. Writing 100.0 makes the math use decimals. For each region’s share of the company total, use an empty window instead: SUM(revenue) OVER ().
2. Running totals
Add ORDER BY inside OVER, and SUM becomes a running (cumulative) total: each row adds up its own revenue and every row before it in the partition.
SELECT month, region, revenue,
SUM(revenue) OVER (PARTITION BY region ORDER BY month) AS running_total
FROM sales
ORDER BY region, month;Result:
month | region | revenue | running_total |
|---|---|---|---|
| 2026-01 | East | 4200 | 4200 |
| 2026-02 | East | 3900 | 8100 |
| 2026-03 | East | 5100 | 13200 |
| 2026-04 | East | 4800 | 18000 |
| 2026-05 | East | 5600 | 23600 |
| 2026-06 | East | 6100 | 29700 |
| 2026-01 | West | 3100 | 3100 |
| 2026-02 | West | 3600 | 6700 |
| 2026-03 | West | 3600 | 10300 |
| 2026-04 | West | 4400 | 14700 |
| 2026-05 | West | 4100 | 18800 |
| 2026-06 | West | 5000 | 23800 |
The total restarts at 3,100 when the West region begins, because PARTITION BY region gives each region its own window. The last row of each region equals that region’s total from the first example. Running totals answer questions like “how much have we sold this year so far?”
3. Ranking with ROW_NUMBER, RANK, and DENSE_RANK
The three ranking functions all number rows in the order you give them. They differ only in how they handle ties. Here are the West region’s months ranked from best to worst, where February and March tie at $3,600:
SELECT month, region, revenue,
ROW_NUMBER() OVER (PARTITION BY region ORDER BY revenue DESC, month) AS row_num,
RANK() OVER (PARTITION BY region ORDER BY revenue DESC) AS rnk,
DENSE_RANK() OVER (PARTITION BY region ORDER BY revenue DESC) AS dense_rnk
FROM sales
WHERE region = 'West'
ORDER BY row_num;Result:
month | region | revenue | row_num | rnk | dense_rnk |
|---|---|---|---|---|---|
| 2026-06 | West | 5000 | 1 | 1 | 1 |
| 2026-04 | West | 4400 | 2 | 2 | 2 |
| 2026-05 | West | 4100 | 3 | 3 | 3 |
| 2026-02 | West | 3600 | 4 | 4 | 4 |
| 2026-03 | West | 3600 | 5 | 4 | 4 |
| 2026-01 | West | 3100 | 6 | 6 | 5 |
| Function | Ties get… | Numbers after a tie | Use it for |
|---|---|---|---|
ROW_NUMBER() | Different numbers (4 and 5) | Continue: 6 | Picking exactly one row per group, or paging |
RANK() | The same number (4 and 4) | Skip: 6 | Competition-style ranks, like “tied for 4th” |
DENSE_RANK() | The same number (4 and 4) | Don’t skip: 5 | Counting distinct values, like “the 2nd-highest amount” |
With ROW_NUMBER, which of the tied rows comes first is up to the database unless you say otherwise. That’s why the query adds month as a tiebreaker: ORDER BY revenue DESC, month. Always give ROW_NUMBER a tiebreaker, or your results can change from one run to the next.
4. Top N per group
“Show the top 2 months in each region” is one of the most common SQL interview questions, and the natural first attempt doesn’t work. You can’t write WHERE ROW_NUMBER() OVER (…) <= 2, because SQL runs WHERE before it calculates window functions. The fix is to calculate the rank in a common table expression (the WITH part), then filter its results:
WITH ranked AS (
SELECT month, region, revenue,
ROW_NUMBER() OVER (PARTITION BY region ORDER BY revenue DESC, month) AS row_num
FROM sales
)
SELECT month, region, revenue
FROM ranked
WHERE row_num <= 2
ORDER BY region, row_num;Result:
month | region | revenue |
|---|---|---|
| 2026-06 | East | 6100 |
| 2026-05 | East | 5600 |
| 2026-06 | West | 5000 |
| 2026-04 | West | 4400 |
The same pattern answers “most recent order per customer” or “highest-paid employee per department”: number the rows within each group, then keep row 1, or rows 1 through N. Some databases, including Snowflake, BigQuery, and DuckDB, also have a QUALIFY clause that filters on a window function directly. PostgreSQL, MySQL, and SQLite don’t, so the WITH version is the one to learn.

5. Compare to the previous row with LAG and LEAD
LAG(column) reads a value from the row before the current one, in the order you give it. That makes month-over-month change a single subtraction:
SELECT month, region, revenue,
LAG(revenue) OVER (PARTITION BY region ORDER BY month) AS prev_month,
revenue - LAG(revenue) OVER (PARTITION BY region ORDER BY month) AS difference
FROM sales
WHERE region = 'East'
ORDER BY month;Result:
month | region | revenue | prev_month | difference |
|---|---|---|---|---|
| 2026-01 | East | 4200 | NULL | NULL |
| 2026-02 | East | 3900 | 4200 | -300 |
| 2026-03 | East | 5100 | 3900 | 1200 |
| 2026-04 | East | 4800 | 5100 | -300 |
| 2026-05 | East | 5600 | 4800 | 800 |
| 2026-06 | East | 6100 | 5600 | 500 |
January has no earlier month, so LAG returns NULL, and anything calculated from NULL is NULL too. LEAD works the same way but looks forward. Both take two optional extra arguments: how many rows to look back or ahead (the default is 1), and a value to use instead of NULL when there’s no such row:
SELECT month, revenue,
LAG(revenue, 1, 0) OVER (ORDER BY month) AS prev_or_zero,
LEAD(revenue) OVER (ORDER BY month) AS next_month
FROM sales
WHERE region = 'East'
ORDER BY month;Result:
month | revenue | prev_or_zero | next_month |
|---|---|---|---|
| 2026-01 | 4200 | 0 | 3900 |
| 2026-02 | 3900 | 4200 | 5100 |
| 2026-03 | 5100 | 3900 | 4800 |
| 2026-04 | 4800 | 5100 | 5600 |
| 2026-05 | 5600 | 4800 | 6100 |
| 2026-06 | 6100 | 5600 | NULL |
Be careful with that default. A 0 for “no previous month” would make January look like a $4,200 jump in a change calculation, so it’s usually better to leave it NULL.
6. Moving averages with window frames
A moving average smooths out noisy data by averaging each value with the ones just before it. You get one by adding a frame to the window:
SELECT month, region, revenue,
ROUND(AVG(revenue) OVER (
PARTITION BY region
ORDER BY month
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
), 1) AS moving_avg_3
FROM sales
WHERE region = 'East'
ORDER BY month;Result:
month | region | revenue | moving_avg_3 |
|---|---|---|---|
| 2026-01 | East | 4200 | 4200.0 |
| 2026-02 | East | 3900 | 4050.0 |
| 2026-03 | East | 5100 | 4400.0 |
| 2026-04 | East | 4800 | 4600.0 |
| 2026-05 | East | 5600 | 5166.7 |
| 2026-06 | East | 6100 | 5500.0 |
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW means “this row and the two before it,” so each month is averaged with the two months before it. The first two months have fewer rows to average: January’s average is just January, and February’s averages two months. Other frames you’ll see:
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW: from the first row up to this one, a running total.ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING: the row before, this row, and the row after.ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING: the whole partition.
The default frame trap: ROWS vs. RANGE
This one catches experienced analysts. When you write ORDER BY in a window and no frame, the database uses a default frame: RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. RANGE treats rows with the same ORDER BY value as a single step, so tied rows are all included together.
Here’s a company-wide running total ordered only by month, for the first three months. Each month has two rows, one per region, and they tie on month:
SELECT month, region, revenue,
SUM(revenue) OVER (ORDER BY month) AS default_frame,
SUM(revenue) OVER (ORDER BY month, region
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS rows_frame
FROM sales
WHERE month <= '2026-03'
ORDER BY month, region;Result:
month | region | revenue | default_frame | rows_frame |
|---|---|---|---|---|
| 2026-01 | East | 4200 | 7300 | 4200 |
| 2026-01 | West | 3100 | 7300 | 7300 |
| 2026-02 | East | 3900 | 14800 | 11200 |
| 2026-02 | West | 3600 | 14800 | 14800 |
| 2026-03 | East | 5100 | 23500 | 19900 |
| 2026-03 | West | 3600 | 23500 | 23500 |
In the default_frame column, both January rows show 7,300, the total for all of January, instead of 4,200 and then 7,300. The rows_frame column fixes it in two ways: ROWS counts physical rows instead of tied groups, and adding region to the ORDER BY makes the order unique. If your running total “jumps” or repeats a number, look for ties in the ORDER BY.
Reuse a window with the WINDOW clause
When several columns use the same window, you can name it once with a WINDOW clause, after WHERE, GROUP BY, and HAVING, and refer to it by name:
SELECT month, region, revenue,
SUM(revenue) OVER w AS running_total,
LAG(revenue) OVER w AS prev_month
FROM sales
WINDOW w AS (PARTITION BY region ORDER BY month)
ORDER BY region, month;Result:
month | region | revenue | running_total | prev_month |
|---|---|---|---|---|
| 2026-01 | East | 4200 | 4200 | NULL |
| 2026-02 | East | 3900 | 8100 | 4200 |
| 2026-03 | East | 5100 | 13200 | 3900 |
| 2026-04 | East | 4800 | 18000 | 5100 |
| 2026-05 | East | 5600 | 23600 | 4800 |
| 2026-06 | East | 6100 | 29700 | 5600 |
| 2026-01 | West | 3100 | 3100 | NULL |
| 2026-02 | West | 3600 | 6700 | 3100 |
| 2026-03 | West | 3600 | 10300 | 3600 |
| 2026-04 | West | 4400 | 14700 | 3600 |
| 2026-05 | West | 4100 | 18800 | 4400 |
| 2026-06 | West | 5000 | 23800 | 4100 |
PostgreSQL, MySQL, SQLite, and DuckDB support named windows. SQL Server added them in SQL Server 2022, so on older versions, repeat the window in full.
Practice problems
Try each one yourself before opening the answer. All three use the same sales table.
1. Find each region’s worst month by revenue. If two months tie for worst, show both.
Show the answer
RANK() instead of ROW_NUMBER() so that ties both get rank 1, sorted from lowest revenue up:
WITH ranked AS (
SELECT month, region, revenue,
RANK() OVER (PARTITION BY region ORDER BY revenue) AS rnk
FROM sales
)
SELECT region, month, revenue
FROM ranked
WHERE rnk = 1
ORDER BY region;region | month | revenue |
|---|---|---|
| East | 2026-02 | 3900 |
| West | 2026-01 | 3100 |
2. Calculate the month-over-month percentage change in revenue for each region, rounded to one decimal place.
Show the answer
Subtract the previous month, divide by it, and multiply by 100.0. A named window saves writing the OVER clause twice:
SELECT month, region, revenue,
ROUND(100.0 * (revenue - LAG(revenue) OVER w) / LAG(revenue) OVER w, 1) AS pct_change
FROM sales
WINDOW w AS (PARTITION BY region ORDER BY month)
ORDER BY region, month;month | region | revenue | pct_change |
|---|---|---|---|
| 2026-01 | East | 4200 | NULL |
| 2026-02 | East | 3900 | -7.1 |
| 2026-03 | East | 5100 | 30.8 |
| 2026-04 | East | 4800 | -5.9 |
| 2026-05 | East | 5600 | 16.7 |
| 2026-06 | East | 6100 | 8.9 |
| 2026-01 | West | 3100 | NULL |
| 2026-02 | West | 3600 | 16.1 |
| 2026-03 | West | 3600 | 0.0 |
| 2026-04 | West | 4400 | 22.2 |
| 2026-05 | West | 4100 | -6.8 |
| 2026-06 | West | 5000 | 22.0 |
3. For the West region, show how far below the region’s best month each month was.
Show the answer
A window with no ORDER BY, MAX(revenue) OVER (PARTITION BY region), puts the best month’s revenue on every row:
SELECT month, region, revenue,
revenue - MAX(revenue) OVER (PARTITION BY region) AS below_best
FROM sales
WHERE region = 'West'
ORDER BY month;month | region | revenue | below_best |
|---|---|---|---|
| 2026-01 | West | 3100 | -1900 |
| 2026-02 | West | 3600 | -1400 |
| 2026-03 | West | 3600 | -1400 |
| 2026-04 | West | 4400 | -600 |
| 2026-05 | West | 4100 | -900 |
| 2026-06 | West | 5000 | 0 |
Window functions cheat sheet
| Function | What it returns | Needs ORDER BY? |
|---|---|---|
SUM, AVG, COUNT, MIN, MAX | The total, average, count, smallest, or largest value in the window | No, but adding it makes a running calculation |
ROW_NUMBER() | 1, 2, 3… with no ties | Yes |
RANK() | Rank with gaps after ties: 1, 2, 2, 4 | Yes |
DENSE_RANK() | Rank without gaps: 1, 2, 2, 3 | Yes |
NTILE(n) | Splits rows into n roughly equal buckets, such as quartiles with NTILE(4) | Yes |
LAG(col, n, default) | The value n rows before the current row | Yes |
LEAD(col, n, default) | The value n rows after the current row | Yes |
FIRST_VALUE(col) | The value in the window’s first row | Yes |
LAST_VALUE(col) | The value in the window’s last row. With the default frame that’s the current row, so add ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING | Yes |
Common errors
| What you see | Likely cause | Fix |
|---|---|---|
| “Window functions are not allowed in WHERE” (or similar) | Filtering on a window function | Calculate it in a WITH query or subquery, then filter the result |
A syntax error near OVER | An old database: MySQL before 8.0 or SQLite before 3.25 | Upgrade, or use an online playground |
A syntax error on a column alias like rank | Function names such as RANK are reserved words in MySQL | Use another alias, such as rnk |
| Percentages are all 0 or whole numbers | Whole-number division | Multiply by 100.0, not 100 |
| A running total repeats the same number | Ties in the ORDER BY with the default RANGE frame | Add a tiebreaker column or use a ROWS frame |
ROW_NUMBER results change between runs | Ties with no tiebreaker | Add another column to the window’s ORDER BY |
Where to practice next
The best way to make window functions stick is to use them on data you care about: your own spending, a sports dataset, or a public dataset from your field. Try a running total, a top 3 per group, and a month-over-month change on it.
If you’d like a structured course, DataCamp’s PostgreSQL Summary Stats and Window Functions course covers everything here plus NTILE, FIRST_VALUE, and pivoting with CROSSTAB, ROLLUP, and CUBE, using Olympics data. DataCamp’s free plan opens the first chapter of every course, and this course is part of the Associate Data Analyst in SQL track, which we reviewed. Our DataCamp review covers the plans and prices.
*We may earn a commission when you click through these links.
If you’re building toward a data engineering job instead, see our review of the Associate Data Engineer in SQL track. And if you’re new to programming in general, our 10 JavaScript practice problems cover the problem-solving side.
From Michael, Hack Reactor ’16: If I were preparing for a data analyst interview, window functions are where I’d spend my SQL practice time. Joins and GROUP BY are expected; being able to write “top 3 per group” or a running total without looking anything up is what makes an answer stand out. Practice until you can explain why the WHERE version fails, not just write the WITH version.
SQL Window Functions FAQ
What is a window function in SQL?
A function that calculates a value for each row from a set of related rows, called the window, without merging those rows together. You write it as a function followed by an OVER clause, for example SUM(revenue) OVER (PARTITION BY region).
What is the difference between GROUP BY and PARTITION BY?
GROUP BY collapses each group into a single row. PARTITION BY, inside a window function’s OVER clause, splits rows into groups for the calculation but keeps every row in the result.
Can you use a window function in a WHERE clause?
No. SQL evaluates WHERE before window functions, so the value doesn’t exist yet. Calculate it in a WITH query (a common table expression) or a subquery, then filter on it. Some warehouses, such as Snowflake and BigQuery, offer a QUALIFY clause for this.
What is the difference between RANK and DENSE_RANK?
Both give tied rows the same rank. RANK then skips numbers (1, 2, 2, 4), while DENSE_RANK doesn’t (1, 2, 2, 3). ROW_NUMBER never gives two rows the same number.
Does MySQL support window functions?
Yes, from MySQL 8.0. SQLite supports them from version 3.25, and PostgreSQL, SQL Server, Oracle, BigQuery, Snowflake, and DuckDB all support them.
Are window functions asked in SQL interviews?
They’re among the most common topics in data analyst and data engineering SQL interviews, especially “top N per group,” running totals, and comparing a row to the previous one with LAG.
Advertiser disclosure: Some companies on this page are affiliate partners. We earn a commission when you buy through our links, at no extra cost to you. Commissions don’t affect our rankings or reviews. How we make money
Michael has a diverse background in software engineering, mechanical engineering, economics, and management. After a successful career in mechanical engineering, Michael decided to become a software engineer and attended the Hack Reactor coding bootcamp. Michael enjoys writing about his experiences and helping others start their journeys in software development.
