Window Functions
Add a per-group number such as an average next to every row without collapsing the rows, using OVER and PARTITION BY.
Calculate across rows, keep every row
A window function calculates a value from a set of rows related to the current row, but unlike GROUP BY it does not collapse them. Every input row stays in the output, and the calculated value is added next to it.
A window function call always has an OVER (...) clause right after it. PARTITION BY inside OVER splits the rows into groups called partitions, and the function is calculated separately in each one.
Detail and summary on one row
"Show every player and their team's average" needs both the single row and the group value. With GROUP BY you would need a join back to the table. A window function gives it in one step.
Each player next to the team average
SELECT name, team, points,
avg(points) OVER (PARTITION BY team) AS team_avg
FROM players;All 8 players are returned. Asha, Chen and Fay each show 27.5 (Red's average of 31 and 24, since NULL is skipped). Ben, Eli and Hana show 17.0. Dara and Gus show 32.0.
OVER () with nothing inside means one window of all rows, so sum(points) OVER () puts the same total, 153, on every row. Any aggregate, such as count, sum, avg, min or max, can be used as a window function.
Collapse or keep the rows
Compare GROUP BY with the window versions, then switch on the WHERE filter and watch the window values change.
| nametext | teamtext | pointsinteger | team_avgbigint | partition |
|---|---|---|---|---|
| Asha | Red | 31 | 27.5 | Red |
| Ben | Blue | 17 | 17 | Blue |
| Chen | Red | NULL | 27.5 | Red |
| Dara | Green | 24 | 32 | Green |
| Eli | Blue | NULL | 17 | Blue |
| Fay | Red | 24 | 27.5 | Red |
| Gus | Green | 40 | 32 | Green |
| Hana | Blue | 17 | 17 | Blue |
The window function keeps every player and adds the average of that player's team next to each row. Rows are not collapsed. Chen is still in the result, next to Red's average.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- A window function calculates a value across related rows without collapsing them.
- OVER (PARTITION BY ...) splits the rows into partitions, and OVER () is the whole table.
- Window functions run after WHERE, GROUP BY and HAVING, so rows removed by WHERE are not seen.
- They are allowed only in SELECT and ORDER BY. To filter on one, use a subquery or CTE.
Done with this concept?
Mark it complete to track your progress. No login needed.