Window Functions
Lesson 15 of 20Rank rows without squashing them — watch RANK() OVER PARTITION stamp every employee with a per-department rank.
Aggregate without collapsing
GROUP BY squashes each group into one row. Window functions compute over a group too — but every original row stays in the result, decorated with the calculation.
OVER opens a window
RANK() OVER (...) tells the engine: look at a set of rows, compute, then write the answer back onto each row.
PARTITION BY splits
PARTITION BY dept makes independent windows; every calculation restarts inside each one.
ORDER BY inside
ORDER BY salary DESC lines up the rows of a window so ranks can be assigned.
RANK vs ROW_NUMBER
ROW_NUMBER numbers 1, 2, 3 with no ties; RANK gives equal rows equal ranks and skips ahead after a tie.
Standardized
Window functions became part of the official SQL standard.
PostgreSQL 8.4
One of the first major engines to ship full window function support.
MySQL 8.0
MySQL added OVER (PARTITION BY ...) — late but very welcome.
Watch each department rank its own salaries
Press play: rows are split into per-department windows, sorted inside each one, then stamped with a rank.
SELECT name, dept, salary,
RANK() OVER (PARTITION BY dept
ORDER BY salary DESC) AS rank_in_dept
FROM employees
ORDER BY dept, salary DESC;| id | name | dept | salary | manager_id |
|---|---|---|---|---|
| 1 | Ava | Engineering | 92000 | 1 |
| 2 | Ben | Engineering | 74000 | 1 |
| 3 | Emma | Engineering | 81000 | 1 |
| 4 | Chloe | Sales | 68000 | 1 |
| 5 | Dev | Sales | 55000 | 4 |
| 6 | Finn | Marketing | 62000 | 1 |
| name | dept | salary | rank_in_dept |
|---|---|---|---|
| press play — rows will appear here |
PARTITION BY dept slices the 6 rows into three independent windows: Engineering, Sales and Marketing.
How a window function runs
Windows are built after the rows are read, but before anything is handed back to you.
Match the window vocabulary
Click a term, then click its description to lock the pair.
Predict the global numbering
Same trick, but no PARTITION BY this time. What does ROW_NUMBER produce?
1SELECT name,2ROW_NUMBER() OVER (ORDER BY salary DESC) AS pos3FROM employees;
Hint: No PARTITION BY means one window over the whole table. ROW_NUMBER numbers strictly 1, 2, 3 by salary, highest first.
Key takeaways
Window functions compute over a set of rows but keep every row visible.
PARTITION BY restarts the calculation for each group.
RANK allows ties and skips; ROW_NUMBER never ties.
GROUP BY shrinks the result; a window function decorates it.
Add ORDER BY inside OVER whenever the order matters for the ranking.