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 single most powerful analytical feature in SQL.
Aggregates that keep the rows
The OVER() clause turns an aggregate into a window function. Here the average is shown next to every row, not instead of them:
SELECT name, package,AVG(package) OVER () AS overall_avg,package - AVG(package) OVER () AS diff_from_avgFROM students;
Ranking functions
| Function | Gives |
|---|---|
ROW_NUMBER() | A unique 1,2,3… (ties broken arbitrarily) |
RANK() | Ties share a rank, then skips (1,1,3) |
DENSE_RANK() | Ties share a rank, no skip (1,1,2) |
NTILE(n) | Splits rows into n buckets (quartiles) |
SELECT name, package,RANK() OVER (ORDER BY package DESC) AS overall_rankFROM students;
PARTITION BY — rank within groups
PARTITION BY restarts the window for each group — top earners within each programme instead of overall:
SELECT name, programme_id, package,RANK() OVER (PARTITION BY programme_id ORDER BY package DESC) AS rank_in_progFROM students;-- Wrap in a CTE and filter rank_in_prog = 1 to get each programme's top earner.
LAG & LEAD — look at neighbours
LAG/LEAD reach to the previous/next row — perfect for month-over-month change:
SELECT month, revenue,LAG(revenue) OVER (ORDER BY month) AS prev_month,revenue - LAG(revenue) OVER (ORDER BY month) AS changeFROM monthly_revenue;
Running totals & frames
Add ORDER BY inside OVER and an aggregate accumulates as a running total:
SELECT month, revenue,SUM(revenue) OVER (ORDER BY monthROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_totalFROM monthly_revenue;
Practice
Rank students by package overall, then within each programme with PARTITION BY. Use a CTE to keep only rank 1 per programme. On a monthly table, compute month-over-month change with LAG and a running total with a windowed SUM.
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/NTILE rank rows with different tie behaviour.
- 04LAG/LEAD reach to previous/next rows for period-over-period comparisons.
- 05An aggregate with OVER(ORDER BY …) becomes a running/cumulative total.
