Window Functions in MySQL

01 Min

Window functions perform calculations across a set of related rows without collapsing them into a single row. Thankfully MySQL 8.0 did introduce them so we can continue practicing our SQL skills without changing the database.

Unlike GROUP BY:

  • window functions preserve individual rows,
  • while still allowing analytical calculations.

There are commonly used for - ranking, leaderboards, running totals etc.


Why Window Functions Matter

Suppose you want each employee’s salary along with their rank inside their department.

With normal aggregation rows would collapse into grouped results.

While Window functions, allow detailed rows and analytical calculations at same time.


Ranking Rows

SELECT
  name,
  department,
  salary,

  RANK() OVER (
    PARTITION BY department
    ORDER BY salary DESC
  ) AS rank

FROM employees;

Understanding the Query

  • PARTITION BY department : Splits rows into groups based on department. Example partitions Engineering, Sales, HR. T

  • ORDER BY salary DESC : Sorts employees within each department by salary. Highest salary receives the best rank.

  • RANK() : Assigns rankings to rows.

Example -

namedepartmentsalaryrank
AliceEngineering1200001
BobEngineering1000002
CharlieEngineering1000002

tied salaries receive the same rank.


Running Totals

Window functions are commonly used for cumulative calculations.

SELECT
  id,
  amount,

  SUM(amount) OVER (
    ORDER BY created_at
  ) AS running_total

FROM payments;

Result -

idamountrunning_total
1100100
2200300
3150450

Each row shows the payment amount plus the cumulative total up to that row.


Common Window Functions

FunctionPurpose
RANK()Ranking with gaps
DENSE_RANK()Ranking without gaps
ROW_NUMBER()Unique row numbering
SUM()Running totals
AVG()Moving averages
LAG()Access previous row
LEAD()Access next row