window functions
aggregates that don't collapse rows. OVER, PARTITION BY, and where windows sit in the logical order.
- address
- everything.analytics.window_functions
- part
- part 4, windows, grouping and recursion
- chapter
- chapter 4 of 11
- reading time
- 8 min
a window function computes something across a set of rows, like an aggregate, and then puts the answer on every row instead of folding them into one. OVER (...) says which rows: PARTITION BY splits them into groups, ORDER BY lines each group up.
windows run after WHERE, GROUP BY and HAVING, and before DISTINCT, ORDER BY and LIMIT. so they can't go in WHERE.
the picture
you know how GROUP BY gets you each department's average salary, and in the same breath throws away every name? and then you join the averages back onto the people to compare them? kinda clunky. a window function is the version that keeps the people.
think of a class photo. GROUP BY is the yearbook page that says "CS: 4 instructors, average 88,750". a window is the same photo with a sticky note on every face: "you're in CS, there are 4 of you, the average here is 88,750". same numbers. nobody left the photo.
- 1SELECT dept, count(*) AS people, round(avg(salary)) AS dept_avg
- 2FROM instructors
- 3GROUP BY dept
- 4ORDER BY dept;
| depttext | peopleint8 | dept_avgnumeric |
|---|---|---|
| CS | 4 | 88750 |
| HIST | 1 | 72000 |
| MATH | 2 | 84000 |
| PHYS | 1 | 90000 |
GROUP BY dept: the eight instructors become four rows, one per department. the names are gone.
OVER (PARTITION BY dept) computes the same count and average per department, and keeps all eight rows, each with its department's numbers.that's the whole idea: an aggregate with OVER after it stops being a GROUP BY aggregate and becomes a window function. the rows go in, the same rows come out, and each one gets a new column.
OVER: which rows each row sees
the parentheses after OVER describe a window: for the current row, which other rows count. there are two knobs, and an empty OVER () uses neither.
SELECT name, dept, salary,
salary - round(avg(salary) OVER (PARTITION BY dept)) AS vs_dept
FROM instructors
ORDER BY dept, salary DESC;| nametext | depttext | salarynumeric | vs_deptnumeric |
|---|---|---|---|
| Hannah Okoye | CS | 98000.00 | 9250.00 |
| Marco Rossi | CS | 91000.00 | 2250.00 |
| Lena Fischer | CS | 87000.00 | -1750.00 |
| Sofia Petrova | CS | 79000.00 | -9750.00 |
| Oliver Grant | HIST | 72000.00 | 0.00 |
| Tomás Ortega | MATH | 85000.00 | 1000.00 |
| Yuki Tanaka | MATH | 83000.00 | -1000.00 |
| Amara Diallo | PHYS | 90000.00 | 0.00 |
Hannah Okoye earns 9,250 more than the CS average. that's the question GROUP BY can't answer in one go: a row's value next to its group's value.
- 1SELECT name, dept, salary,
- 2 count(*) OVER () AS n,
- 3 sum(salary) OVER () AS total
- 4FROM instructors
- 5ORDER BY dept, salary DESC;
| nametext | depttext | salarynumeric | nint8 | totalnumeric |
|---|---|---|---|---|
| Hannah Okoye | CS | 98000.00 | 8 | 685000.00 |
| Marco Rossi | CS | 91000.00 | 8 | 685000.00 |
| Lena Fischer | CS | 87000.00 | 8 | 685000.00 |
| Sofia Petrova | CS | 79000.00 | 8 | 685000.00 |
| Oliver Grant | HIST | 72000.00 | 8 | 685000.00 |
| Tomás Ortega | MATH | 85000.00 | 8 | 685000.00 |
| Yuki Tanaka | MATH | 83000.00 | 8 | 685000.00 |
| Amara Diallo | PHYS | 90000.00 | 8 | 685000.00 |
OVER (): one window holding every row. every row gets the count and the total of all eight.
() is everyone. PARTITION BY gives each department its own window. ORDER BY makes each row see only the rows up to itself, so the count and the sum become running ones.- PARTITION BY splits the rows into independent groups, like GROUP BY's buckets, minus the folding. no PARTITION BY means one partition, the whole result.
- ORDER BY lines up the rows inside each partition. ranking functions need it (row_number, rank and dense_rank), so do
lagandlead(the previous row).
and here's the surprise in the third run: adding ORDER BY to a sum turned it into a running total. an ORDER BY inside OVER also sets a default frame, "from the first row to this one", and the sum reads only its frame. that's on purpose, it's how running totals are written, and it's also the reason window frames is a chapter of its own.
SELECT name, count(*) OVER () AS n
FROM instructors;where windows run
windows have a fixed place in the logical order: after FROM, WHERE, GROUP BY and HAVING, and before DISTINCT, ORDER BY and LIMIT. they see exactly the rows that survived the clauses before them, and nothing they compute is cut until the clauses after them.
- 1SELECT name, dept, salary, rank() OVER w AS dept_rank
- 2FROM instructors
- 3WHERE salary < 95000
- 4WINDOW w AS (PARTITION BY dept ORDER BY salary DESC)
- 5ORDER BY dept_rank, salary DESC
- 6LIMIT 3;
| nametext | depttext | salarynumeric |
|---|---|---|
| Hannah Okoye | CS | 98000.00 |
| Marco Rossi | CS | 91000.00 |
| Lena Fischer | CS | 87000.00 |
| Sofia Petrova | CS | 79000.00 |
| Oliver Grant | HIST | 72000.00 |
| Tomás Ortega | MATH | 85000.00 |
| Yuki Tanaka | MATH | 83000.00 |
| Amara Diallo | PHYS | 90000.00 |
FROM: all eight instructors.
the query that produced this table
dept_rank to seven rows and removes none. ORDER BY can sort on it, and LIMIT cuts last, after every rank is decided.two consequences you'll run into in your first week.
a window function can't go in WHERE, because WHERE runs before windows exist. postgres says so by name:
SELECT name, dept, salary
FROM instructors
WHERE rank() OVER (PARTITION BY dept ORDER BY salary DESC) = 1;the fix is the same as for an alias: compute it one level down, filter one level up.
SELECT name, dept, salary
FROM (
SELECT name, dept, salary,
rank() OVER (PARTITION BY dept ORDER BY salary DESC) AS dept_rank
FROM instructors
) AS ranked
WHERE dept_rank = 1
ORDER BY dept;| nametext | depttext | salarynumeric |
|---|---|---|
| Hannah Okoye | CS | 98000.00 |
| Oliver Grant | HIST | 72000.00 |
| Tomás Ortega | MATH | 85000.00 |
| Amara Diallo | PHYS | 90000.00 |
that's the shape of every "top n per group" query, and top n per group compares it with the other two ways. (HAVING is out for the same reason: it also runs before windows. some engines, duckdb for one, add a QUALIFY clause that filters after windows. postgres doesn't have it.)
a window can run over grouped rows. since GROUP BY has already happened, a window can take the groups as its rows, aggregates included. a window sum of a group count is the classic "percent of total":
SELECT dept,
count(*) AS courses,
round(100.0 * count(*) / sum(count(*)) OVER (), 1) AS pct
FROM courses
GROUP BY dept
ORDER BY dept;| depttext | coursesint8 | pctnumeric |
|---|---|---|
| CS | 5 | 41.7 |
| GEN | 1 | 8.3 |
| HIST | 1 | 8.3 |
| MATH | 3 | 25.0 |
| PHYS | 2 | 16.7 |
count(*) is the GROUP BY aggregate, one per department. sum(...) OVER () is a window over the five grouped rows, adding up those counts. CS has 5 of the 12 courses: 41.7%.
naming a window
when several functions share a window, write it once in a WINDOW clause and refer to it by name. it reads better, and postgres computes functions over the same window in one pass over one sort:
SELECT name, dept, salary,
rank() OVER w AS dept_rank,
first_value(name) OVER w AS top_of_dept
FROM instructors
WINDOW w AS (PARTITION BY dept ORDER BY salary DESC)
ORDER BY dept, salary DESC;| nametext | depttext | salarynumeric | dept_rankint8 | top_of_depttext |
|---|---|---|---|---|
| Hannah Okoye | CS | 98000.00 | 1 | Hannah Okoye |
| Marco Rossi | CS | 91000.00 | 2 | Hannah Okoye |
| Lena Fischer | CS | 87000.00 | 3 | Hannah Okoye |
| Sofia Petrova | CS | 79000.00 | 4 | Hannah Okoye |
| Oliver Grant | HIST | 72000.00 | 1 | Oliver Grant |
| Tomás Ortega | MATH | 85000.00 | 1 | Tomás Ortega |
| Yuki Tanaka | MATH | 83000.00 | 2 | Tomás Ortega |
| Amara Diallo | PHYS | 90000.00 | 1 | Amara Diallo |
the plan shows the pass: one WindowAgg node over one sort, for both functions:
EXPLAIN (COSTS OFF)
SELECT name, rank() OVER w, first_value(name) OVER w
FROM instructors
WINDOW w AS (PARTITION BY dept ORDER BY salary DESC)
ORDER BY dept, salary DESC;one sort by dept, salary DESC, then one WindowAgg computing both. (the Window: line prints ORDER BY salary without the DESC; the Sort Key right under it has it. that's how postgres 18.6 prints it, on a real server too, not a different window.) different windows mean more sorts, one WindowAgg each, stacked. how postgres sorts is sorting's business.
keylines
- a window function computes across rows and keeps every row: n rows in, n rows out.
- OVER says which rows: PARTITION BY splits them, ORDER BY lines them up.
- ORDER BY inside OVER also turns aggregates into running ones (the default frame).
- windows run after WHERE, GROUP BY and HAVING, before DISTINCT, ORDER BY and LIMIT.
- to filter on a window function, compute it in a subquery and filter outside.