Skip to main content
Albero Academy

Window Functions

Rank rows, compute running totals, and compare each row to its neighbours — without collapsing the result like GROUP BY does.

Chapter 7MySQL16 min readBeginner friendly
  • #MySQL
  • #Window Functions
  • #Analytics

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:

OVER() keeps the rows
SELECT name, package,
AVG(package) OVER () AS overall_avg,
package - AVG(package) OVER () AS diff_from_avg
FROM students;

Ranking functions

FunctionGives
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)
ordered ranking
SELECT name, package,
RANK() OVER (ORDER BY package DESC) AS overall_rank
FROM students;

PARTITION BY — rank within groups

PARTITION BY restarts the window for each group — top earners within each programme instead of overall:

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;
-- 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:

compare to previous period
SELECT month, revenue,
LAG(revenue) OVER (ORDER BY month) AS prev_month,
revenue - LAG(revenue) OVER (ORDER BY month) AS change
FROM monthly_revenue;

Running totals & frames

Add ORDER BY inside OVER and an aggregate accumulates as a running total:

cumulative sum
SELECT month, revenue,
SUM(revenue) OVER (ORDER BY month
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total
FROM 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

  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/NTILE rank rows with different tie behaviour.
  4. 04LAG/LEAD reach to previous/next rows for period-over-period comparisons.
  5. 05An aggregate with OVER(ORDER BY …) becomes a running/cumulative total.