GROUP BY collapses rows into one per group. Window functions compute across a set of rows but keep every row — so you can show each student and their rank within their programme in one query. They're the most powerful analytical feature in SQL.
The OVER clause
SELECT name, package,AVG(package) OVER () AS overall_avg, -- same on every rowpackage - AVG(package) OVER () AS diffFROM students;
Ranking & partitions
| Function | Gives |
|---|---|
ROW_NUMBER() | A unique 1,2,3… (ties broken arbitrarily) |
RANK() | Ties share a rank, then skip (1,1,3) |
DENSE_RANK() | Ties share a rank, no skip (1,1,2) |
LAG()/LEAD() | The previous/next row's value |
SELECT name, programme_id, package,RANK() OVER (PARTITION BY programme_id ORDER BY package DESC) AS rank_in_progFROM students;-- Running total by dateSELECT month, revenue,SUM(revenue) OVER (ORDER BY month) AS running_totalFROM monthly;
Key takeaways
- 01Window functions compute across rows but keep every row — unlike GROUP BY.
- 02OVER() defines the window; PARTITION BY restarts it per group; ORDER BY orders within it.
- 03ROW_NUMBER/RANK/DENSE_RANK rank rows; LAG/LEAD reach to neighbours.
- 04An aggregate with OVER(ORDER BY …) becomes a running total.
