skip to content

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.

fold with =
query.sql
  1. 1SELECT dept, count(*) AS people, round(avg(salary)) AS dept_avg
  2. 2FROM instructors
  3. 3GROUP BY dept
  4. 4ORDER BY dept;
the result for GROUP BY dept
depttextpeopleint8dept_avgnumeric
CS488750
HIST172000
MATH284000
PHYS190000
(4 rows)

GROUP BY dept: the eight instructors become four rows, one per department. the names are gone.

real output, postgres 18.6 (PGlite 0.5.12) · window-functions
switch between the two. GROUP BY folds the eight instructors into four rows. 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.

sqldb=school
SELECT name, dept, salary,
       salary - round(avg(salary) OVER (PARTITION BY dept)) AS vs_dept
FROM instructors
ORDER BY dept, salary DESC;
output, from postgres 18.6
SELECT 8
nametextdepttextsalarynumericvs_deptnumeric
Hannah OkoyeCS98000.009250.00
Marco RossiCS91000.002250.00
Lena FischerCS87000.00-1750.00
Sofia PetrovaCS79000.00-9750.00
Oliver GrantHIST72000.000.00
Tomás OrtegaMATH85000.001000.00
Yuki TanakaMATH83000.00-1000.00
Amara DialloPHYS90000.000.00
(8 rows)

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.

OVER =
query.sql
  1. 1SELECT name, dept, salary,
  2. 2 count(*) OVER () AS n,
  3. 3 sum(salary) OVER () AS total
  4. 4FROM instructors
  5. 5ORDER BY dept, salary DESC;
the result for ()
nametextdepttextsalarynumericnint8totalnumeric
Hannah OkoyeCS98000.008685000.00
Marco RossiCS91000.008685000.00
Lena FischerCS87000.008685000.00
Sofia PetrovaCS79000.008685000.00
Oliver GrantHIST72000.008685000.00
Tomás OrtegaMATH85000.008685000.00
Yuki TanakaMATH83000.008685000.00
Amara DialloPHYS90000.008685000.00
(8 rows)

OVER (): one window holding every row. every row gets the count and the total of all eight.

real output, postgres 18.6 (PGlite 0.5.12) · window-functions
four windows over the same eight rows. () 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 lag and lead (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.

predict the output
sql
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.

query.sqlstep 1: FROM
  1. 1SELECT name, dept, salary, rank() OVER w AS dept_rank
  2. 2FROM instructors
  3. 3WHERE salary < 95000
  4. 4WINDOW w AS (PARTITION BY dept ORDER BY salary DESC)
  5. 5ORDER BY dept_rank, salary DESC
  6. 6LIMIT 3;
the table after FROM
nametextdepttextsalarynumeric
Hannah OkoyeCS98000.00
Marco RossiCS91000.00
Lena FischerCS87000.00
Sofia PetrovaCS79000.00
Oliver GrantHIST72000.00
Tomás OrtegaMATH85000.00
Yuki TanakaMATH83000.00
Amara DialloPHYS90000.00
(8 rows)

FROM: all eight instructors.

the query that produced this table
SELECT name, dept, salary FROM instructors ORDER BY dept, salary DESC
clause 1/5
real output, postgres 18.6 (PGlite 0.5.12) · window-functions
step through. WHERE drops Hannah Okoye before the window exists, so Marco Rossi ranks first in CS. the window adds 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:

sqldb=school
SELECT name, dept, salary
FROM instructors
WHERE rank() OVER (PARTITION BY dept ORDER BY salary DESC) = 1;
output, from postgres 18.6
ERROR 42P20: window functions are not allowed in WHERE
3 │ WHERE rank() OVER (PARTITION BY dept ORDER BY salary DESC) = 1;
at line 3, column 7

the fix is the same as for an alias: compute it one level down, filter one level up.

sqldb=school
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;
output, from postgres 18.6
SELECT 4
nametextdepttextsalarynumeric
Hannah OkoyeCS98000.00
Oliver GrantHIST72000.00
Tomás OrtegaMATH85000.00
Amara DialloPHYS90000.00
(4 rows)

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":

sqldb=school
SELECT dept,
       count(*) AS courses,
       round(100.0 * count(*) / sum(count(*)) OVER (), 1) AS pct
FROM courses
GROUP BY dept
ORDER BY dept;
output, from postgres 18.6
SELECT 5
depttextcoursesint8pctnumeric
CS541.7
GEN18.3
HIST18.3
MATH325.0
PHYS216.7
(5 rows)

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:

sqldb=school
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;
output, from postgres 18.6
SELECT 8
nametextdepttextsalarynumericdept_rankint8top_of_depttext
Hannah OkoyeCS98000.001Hannah Okoye
Marco RossiCS91000.002Hannah Okoye
Lena FischerCS87000.003Hannah Okoye
Sofia PetrovaCS79000.004Hannah Okoye
Oliver GrantHIST72000.001Oliver Grant
Tomás OrtegaMATH85000.001Tomás Ortega
Yuki TanakaMATH83000.002Tomás Ortega
Amara DialloPHYS90000.001Amara Diallo
(8 rows)

the plan shows the pass: one WindowAgg node over one sort, for both functions:

sqldb=school
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;
output, from postgres 18.6
EXPLAIN
WindowAgg Window: w AS (PARTITION BY dept ORDER BY salary) -> Sort Sort Key: dept, salary DESC -> Seq Scan on instructors

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.