Advertiser Disclosure

SQL Window Functions Explained (With Examples)

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.

Illustration of a SQL result table with a 3-month moving average: the May 2026 row is highlighted as the current row, and the two months before it are shaded as the window frame, 2 preceding rows and the current row

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.

GROUP BY vs. a window function on the same monthly sales table. GROUP BY region returns two rows, East 29,700 and West 23,800, and the months are gone. SUM(revenue) OVER (PARTITION BY region) keeps all 12 monthly rows and adds each region's total, 29,700 or 23,800, beside every month

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:

regiontotal
East29700
West23800

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:

monthregionrevenueregion_total
2026-01East420029700
2026-02East390029700
2026-03East510029700
2026-04East480029700
2026-05East560029700
2026-06East610029700
2026-01West310023800
2026-02West360023800
2026-03West360023800
2026-04West440023800
2026-05West410023800
2026-06West500023800

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:

The three parts of the OVER clause, in order: PARTITION BY splits rows into groups and the calculation starts over for each; ORDER BY sorts rows inside each group and is needed for rankings, LAG and LEAD; the frame, such as ROWS BETWEEN 2 PRECEDING AND CURRENT ROW, narrows the window to rows around the current one, for example for a 3-month moving average
  • PARTITION BY splits 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 BY sorts the rows inside each partition. It’s required for ranking functions and for LAG and LEAD, 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:

monthregionrevenuepct_of_region
2026-01East420014.1
2026-02East390013.1
2026-03East510017.2
2026-04East480016.2
2026-05East560018.9
2026-06East610020.5
2026-01West310013.0
2026-02West360015.1
2026-03West360015.1
2026-04West440018.5
2026-05West410017.2
2026-06West500021.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:

monthregionrevenuerunning_total
2026-01East42004200
2026-02East39008100
2026-03East510013200
2026-04East480018000
2026-05East560023600
2026-06East610029700
2026-01West31003100
2026-02West36006700
2026-03West360010300
2026-04West440014700
2026-05West410018800
2026-06West500023800

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:

monthregionrevenuerow_numrnkdense_rnk
2026-06West5000111
2026-04West4400222
2026-05West4100333
2026-02West3600444
2026-03West3600544
2026-01West3100665
FunctionTies get…Numbers after a tieUse it for
ROW_NUMBER()Different numbers (4 and 5)Continue: 6Picking exactly one row per group, or paging
RANK()The same number (4 and 4)Skip: 6Competition-style ranks, like “tied for 4th”
DENSE_RANK()The same number (4 and 4)Don’t skip: 5Counting 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:

monthregionrevenue
2026-06East6100
2026-05East5600
2026-06West5000
2026-04West4400

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.

The logical order SQL runs a query in: FROM, WHERE, GROUP BY, HAVING, window functions, SELECT, ORDER BY, LIMIT. Because WHERE runs before window functions, WHERE ROW_NUMBER() OVER (...) <= 2 does not work; instead, number the rows in a WITH query and filter its result

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:

monthregionrevenueprev_monthdifference
2026-01East4200NULLNULL
2026-02East39004200-300
2026-03East510039001200
2026-04East48005100-300
2026-05East56004800800
2026-06East61005600500

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:

monthrevenueprev_or_zeronext_month
2026-01420003900
2026-02390042005100
2026-03510039004800
2026-04480051005600
2026-05560048006100
2026-0661005600NULL

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:

monthregionrevenuemoving_avg_3
2026-01East42004200.0
2026-02East39004050.0
2026-03East51004400.0
2026-04East48004600.0
2026-05East56005166.7
2026-06East61005500.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:

monthregionrevenuedefault_framerows_frame
2026-01East420073004200
2026-01West310073007300
2026-02East39001480011200
2026-02West36001480014800
2026-03East51002350019900
2026-03West36002350023500

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:

monthregionrevenuerunning_totalprev_month
2026-01East42004200NULL
2026-02East390081004200
2026-03East5100132003900
2026-04East4800180005100
2026-05East5600236004800
2026-06East6100297005600
2026-01West31003100NULL
2026-02West360067003100
2026-03West3600103003600
2026-04West4400147003600
2026-05West4100188004400
2026-06West5000238004100

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;
regionmonthrevenue
East2026-023900
West2026-013100

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;
monthregionrevenuepct_change
2026-01East4200NULL
2026-02East3900-7.1
2026-03East510030.8
2026-04East4800-5.9
2026-05East560016.7
2026-06East61008.9
2026-01West3100NULL
2026-02West360016.1
2026-03West36000.0
2026-04West440022.2
2026-05West4100-6.8
2026-06West500022.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;
monthregionrevenuebelow_best
2026-01West3100-1900
2026-02West3600-1400
2026-03West3600-1400
2026-04West4400-600
2026-05West4100-900
2026-06West50000

Window functions cheat sheet

FunctionWhat it returnsNeeds ORDER BY?
SUM, AVG, COUNT, MIN, MAXThe total, average, count, smallest, or largest value in the windowNo, but adding it makes a running calculation
ROW_NUMBER()1, 2, 3… with no tiesYes
RANK()Rank with gaps after ties: 1, 2, 2, 4Yes
DENSE_RANK()Rank without gaps: 1, 2, 2, 3Yes
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 rowYes
LEAD(col, n, default)The value n rows after the current rowYes
FIRST_VALUE(col)The value in the window’s first rowYes
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 FOLLOWINGYes

Common errors

What you seeLikely causeFix
“Window functions are not allowed in WHERE” (or similar)Filtering on a window functionCalculate it in a WITH query or subquery, then filter the result
A syntax error near OVERAn old database: MySQL before 8.0 or SQLite before 3.25Upgrade, or use an online playground
A syntax error on a column alias like rankFunction names such as RANK are reserved words in MySQLUse another alias, such as rnk
Percentages are all 0 or whole numbersWhole-number divisionMultiply by 100.0, not 100
A running total repeats the same numberTies in the ORDER BY with the default RANGE frameAdd a tiebreaker column or use a ROWS frame
ROW_NUMBER results change between runsTies with no tiebreakerAdd 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.