13. Window Functions
Rankings, running totals, and rows that see other rows.
The lesson
Window Functions
You can count, sum, join and rank by now. But every aggregate you've used so far has a price: GROUP BY collapses rows. SELECT genre_id, MAX(duration_sec) FROM tracks GROUP BY genre_id gives you eight rows — and you can't tell anymore which track holds each record.
What if you want a ranking that lives next to every row instead of replacing them? That's what window functions are for.
The problem GROUP BY can't solve
Think about what you'd want for a "longest songs" screen: the full list of 49 tracks, in order, with a position number on each. That's a question where the answer keeps every row and adds information about how each row compares to the others.
Window functions answer exactly this kind of question. A window function is a function that looks at the set of rows related to the current row — its "window" — and returns a value computed from that set. Unlike GROUP BY, it does not collapse the rows. Each row stays, and the window result tags along beside it.
Anatomy of a window call
SELECT title, duration_sec,
ROW_NUMBER() OVER (ORDER BY duration_sec DESC) AS position
FROM tracks;
Three moving parts:
- The function — here
ROW_NUMBER(), which numbers rows 1, 2, 3… from the start of the window. OVER (...)— this is what turns an ordinary aggregate into a window call. It also happens to be where the window gets defined.- The window itself — here just
ORDER BY duration_sec DESC. It lines the rows up like people in a queue; the function then counts along the queue.
Read it like English: number the rows, in the order of longest duration first. Every track keeps its row — Nocturne No. 2 gets position 1, Crossroads (Live) gets 3, and Copper Wire brings up the rear at 49.
The ranking family: ROW_NUMBER, RANK, DENSE_RANK
Our catalog has exactly two prices — 1.29 and 0.99 — so any ranking over unit_price is full of ties. That makes it the perfect place to see the three ranking functions side by side:
| unit_price | row_number | rank | dense_rank |
|---|---|---|---|
| 1.29 | 1 | 1 | 1 |
| 1.29 | 2 | 1 | 1 |
| … | … | … | … |
| 1.29 | 20 | 1 | 1 |
| 0.99 | 21 | 21 | 2 |
| 0.99 | 22 | 21 | 2 |
| … | … | … | … |
| 0.99 | 49 | 21 | 2 |
ROW_NUMBER()never ties. It just counts: 1, 2, 3… 49. On equal values, the order between the tied rows is arbitrary but consistent.RANK()gives every tied row the same rank, then skips ahead — the 0.99 tracks don't start at 2, they start at 21.DENSE_RANK()also ties, but doesn't skip: the next price level simply goes up by one.
Tie-heavy columns like unit_price are exactly where RANK vs DENSE_RANK matter. If you're making a leaderboard where "two for first place" should be followed by third place, that's RANK. If you're cutting the catalog into tiers, DENSE_RANK keeps the tiers numbered neatly.
PARTITION BY: windows inside groups
PARTITION BY splits the rows into groups before the window function runs — but unlike GROUP BY, it keeps every row:
SELECT title, genre_id,
RANK() OVER (PARTITION BY genre_id ORDER BY duration_sec DESC) AS genre_rank
FROM tracks;
Now the ranking restarts for each genre: Crossroads (Live) is 1 within Rock, Meridian Blue is 1 within Jazz, and so on. The rows are still all there — the partition only decides which rows each rank compares against.
GROUP BY collapses; PARTITION BY annotates. That one sentence separates two of the most confusing features in SQL.
Running totals: SUM over a window
Aggregates can be windowed too — that's how running totals work. The same SUM you've used since chapter 5, given an OVER clause with an ordering:
SELECT invoice_date, total,
SUM(total) OVER (ORDER BY invoice_date) AS running_total
FROM invoices
ORDER BY invoice_date;
For each row, the window is "everything from the start up to the current row". The first invoice shows 2.58; the second shows 2.58 + 4.56 = 7.14; the last shows the grand total, 53.61. The ORDER BY inside OVER decides what "so far" means — the window follows the same ordering.
Frames: ROWS BETWEEN
A running total always looks back to the start. But sometimes you want a sliding window — say, a 3-month moving average of monthly revenue, where each month's window is just "this month and the two before it":
SELECT month, revenue,
ROUND(AVG(revenue) OVER (ORDER BY month
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 2) AS moving_avg
FROM (SELECT strftime('%Y-%m', invoice_date) AS month, SUM(total) AS revenue
FROM invoices GROUP BY strftime('%Y-%m', invoice_date));
The frame clause — ROWS BETWEEN 2 PRECEDING AND CURRENT ROW — pins the window to a fixed number of rows around the current one. The default frame, when you don't write one, runs from the start of the partition to the current row (which is why SUM(total) OVER (ORDER BY invoice_date) makes a running total for free). Once you want the window to slide, write a frame.
Looking at neighbors: LAG and LEAD
Sometimes the current row isn't the point — its neighbor is. LAG(column) reaches back to the previous row; LEAD(column) reaches forward. Perfect for "days between invoices":
SELECT invoice_date,
julianday(invoice_date) - julianday(LAG(invoice_date) OVER (ORDER BY invoice_date)) AS days_since_last
FROM invoices;
January 15th to February 3rd is 19 days; February 3rd to April 10th is 66. The very first row has no predecessor, so LAG returns NULL — that's correct, not a bug. NULL is SQL's honest way of saying "there is no previous row".
The WHERE trap
Window functions are computed after WHERE and GROUP BY have done their work. You cannot write:
SELECT ... WHERE ROW_NUMBER() OVER (...) <= 2; -- error
The database doesn't even know the rank exists yet at WHERE time. The fix is the pattern that appears again in the boss exercise: compute the window in an inner query, then filter outside:
SELECT title, genre_id, duration_sec
FROM (SELECT title, genre_id, duration_sec,
ROW_NUMBER() OVER (PARTITION BY genre_id ORDER BY duration_sec DESC) AS rn
FROM tracks)
WHERE rn <= 2;
The inner query attaches ranks; the outer one keeps only the top two per genre. A window function is an output, not a filter — if you want to filter by it, wrap it.
What you just learned
- A window function computes over the rows related to the current row without collapsing them, unlike
GROUP BY. OVER (ORDER BY ...)lines rows up in a sequence;PARTITION BYsplits that sequence into groups.ROW_NUMBERnever ties;RANKties and leaves gaps;DENSE_RANKties without gaps.- Aggregates become running totals with
SUM(...) OVER (ORDER BY ...); frame clauses (ROWS BETWEEN ...) make them slide. LAG/LEADread neighboring rows — and the first row'sLAGisNULL.- Window results can't go in
WHERE— wrap the query and filter outside.
Dialect note. Window functions exist in every modern database: PostgreSQL, MySQL 8+, SQL Server, and of course SQLite. MySQL before version 8 has none of this — one of the rare big gaps. Syntax is nearly identical everywhere; PostgreSQL additionally offers a
FILTERclause and named windows, which SQLite doesn't have. When in doubt,ROW_NUMBER(),RANK()andSUM(...) OVER (...)behave the same on all of them.
The exercises below are the payoff of the whole course so far — every query you write from now on can see the whole picture at once.