Show contents
Chapter 1 of 7 · 20 min
Window functions
By the end of this chapter, you'll be able to
- Compute an indicator over a group of rows with OVER and PARTITION BY
- Rank rows with ROW_NUMBER, RANK and DENSE_RANK
- Compute running totals, moving averages and changes with LAG
- Filter on the result of a window function thanks to a CTE
OVER: an aggregation that keeps the rows
The sales table holds each seller's figure for each month, from July to October. For September, we want each sale, its rank and its share of the month's total:
SELECT month, seller, amount,
RANK() OVER (PARTITION BY month ORDER BY amount DESC) AS rank,
ROUND(100.0 * amount / SUM(amount) OVER (PARTITION BY month), 1) AS share_pct
FROM sales
WHERE month = '2026-09'
ORDER BY rank, seller;
month | seller | amount | rank | share_pct
2026-09 | Awa | 1600 | 1 | 32.7
2026-09 | Chloé | 1250 | 2 | 25.5
2026-09 | Diego | 1250 | 2 | 25.5
2026-09 | Bilal | 800 | 4 | 16.3
SUM(amount) OVER (PARTITION BY month)computes the sum of the row's month, without grouping: each row stays, and receives the total of its partition (here 4,900).RANK() OVER (PARTITION BY month ORDER BY amount DESC)numbers the rows of each partition in the requested order. Chloé and Diego, tied, share 2nd place.100.0 * …guarantees a decimal calculation: if the amounts were stored as integers,100 * 1600 / 4900would be an integer division (32 instead of 32.7).
Chloé and Diego are tied: same rank. Bilal gets rank 4, because RANK skips the shared places.
Text description of the animation
- SQL sorts the rows by partition: here, September's four sales.
- For Awa's row, the window is her whole partition: the sum is 4,900. The row isn't merged.
- In the partition sorted by decreasing amount, Awa comes first: rank 1.
- Chloé and Diego are tied: same rank. Bilal gets rank 4, because RANK skips the shared places.
Ranking: ROW_NUMBER, RANK, DENSE_RANK
The three functions differ only when there are ties. WINDOW w AS (…) names a window to reuse it:
SELECT month, seller, amount,
ROW_NUMBER() OVER w AS rn, RANK() OVER w AS rk, DENSE_RANK() OVER w AS drk
FROM sales
WHERE month = '2026-09'
WINDOW w AS (ORDER BY amount DESC)
ORDER BY rn;
month | seller | amount | rn | rk | drk
2026-09 | Awa | 1600 | 1 | 1 | 1
2026-09 | Chloé | 1250 | 2 | 2 | 2
2026-09 | Diego | 1250 | 3 | 2 | 2
2026-09 | Bilal | 800 | 4 | 4 | 3
| Function | On a tie | Typical use |
|---|---|---|
ROW_NUMBER() | different numbers, arbitrary order | keeping exactly one row per group |
RANK() | same rank, then a gap (1, 2, 2, 4) | sports rankings |
DENSE_RANK() | same rank, no gap (1, 2, 2, 3) | levels, tiers |
Running totals, changes and moving averages
With an ORDER BY in the window, SUM becomes a running total: the window goes from the start of the partition to the current row. LAG(column) reads the value of the previous row (and LEAD, the next one):
SELECT month, amount,
SUM(amount) OVER (ORDER BY month) AS running_total,
amount - LAG(amount) OVER (ORDER BY month) AS change
FROM sales
WHERE seller = 'Awa'
ORDER BY month;
month | amount | running_total | change
2026-07 | 1200 | 1200 | NULL
2026-08 | 1100 | 2300 | -100
2026-09 | 1600 | 3900 | 500
2026-10 | 1700 | 5600 | 100
The first row has no previous row: LAG returns NULL, and so does the change. You can also set the size of the window. The three-month moving average smooths out variations:
WITH monthly AS (
SELECT month, SUM(amount) AS total FROM sales GROUP BY month
)
SELECT month, total,
ROUND(AVG(total) OVER (ORDER BY month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 1) AS avg_3_months
FROM monthly;
month | total | avg_3_months
2026-07 | 4300 | 4300
2026-08 | 4900 | 4600
2026-09 | 4900 | 4700
2026-10 | 5200 | 5000
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW: the current row and the two before it. The first two months don't yet have three months of history: the average covers what exists.
Your turn
Mini-lab: each seller's best monthSQLite
Result
Click “Run”: the SQL engine (about 1 MB) will load in your browser the first time.
A fresh SQLite database is created on every run, in your browser · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Worked exercise
Solved exercise: growth per region
Compute each region's total sales for each month, then its growth as a percentage compared with the previous month of the same region, rounded to one decimal place.
Hint 1
per_region CTE does the GROUP BY region, month. The window function then applies to that result.Hint 2
(total - previous) / previous, with previous = LAG(total) OVER (PARTITION BY region ORDER BY month).Show the solution and common mistakes
WITH per_region AS (
SELECT region, month, SUM(amount) AS total FROM sales GROUP BY region, month
)
SELECT region, month, total,
ROUND(100.0 * (total - LAG(total) OVER (PARTITION BY region ORDER BY month)) / LAG(total) OVER (PARTITION BY region ORDER BY month), 1) AS growth_pct
FROM per_region
ORDER BY region, month;
region | month | total | growth_pct
East | 2026-07 | 2200 | NULL
East | 2026-08 | 2500 | 13.6
East | 2026-09 | 2500 | 0
East | 2026-10 | 2500 | 0
West | 2026-07 | 2100 | NULL
West | 2026-08 | 2400 | 14.3
West | 2026-09 | 2400 | 0
West | 2026-10 | 2700 | 12.5
PARTITION BY region is essential: without it, LAG would compare July in the West with October in the East, the previous row in the overall sort.
Common mistakes:
- Dividing by the current month's total instead of the previous month's: you get the increase's share of the month, not the growth.
- Putting
SUM(amount)andLAGin the same query as theGROUP BYwithout a CTE: it's possible (LAG(SUM(amount)) OVER …), but much less readable.
Summary
- 1A window function (… OVER (…)) computes over a group of rows without merging them.
- 2PARTITION BY splits the rows into groups; ORDER BY in the window sets the calculation order.
- 3ROW_NUMBER, RANK and DENSE_RANK differ when there are ties.
- 4SUM … OVER (ORDER BY …) gives a running total; LAG and LEAD read the previous or next row.
- 5To filter on a window function, compute it in a CTE then filter.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.