Skip to main content
Albero Academy

Window Functions

Rank, run totals, and compare to neighbours — without collapsing rows.

Advanced Queries10 min

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

aggregate without collapsing
SELECT name, package,
AVG(package) OVER () AS overall_avg, -- same on every row
package - AVG(package) OVER () AS diff
FROM students;

Ranking & partitions

FunctionGives
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
rank within each programme
SELECT name, programme_id, package,
RANK() OVER (PARTITION BY programme_id ORDER BY package DESC) AS rank_in_prog
FROM students;
-- Running total by date
SELECT month, revenue,
SUM(revenue) OVER (ORDER BY month) AS running_total
FROM monthly;

Key takeaways

  1. 01Window functions compute across rows but keep every row — unlike GROUP BY.
  2. 02OVER() defines the window; PARTITION BY restarts it per group; ORDER BY orders within it.
  3. 03ROW_NUMBER/RANK/DENSE_RANK rank rows; LAG/LEAD reach to neighbours.
  4. 04An aggregate with OVER(ORDER BY …) becomes a running total.

Finished this chapter?

Mark it complete to track your progress through SQL.