TExcelTAD
Home › MySQL › MySQL Window Functions

MySQL Window Functions

GROUP BY collapses rows: one row per group. Window functions, available since MySQL 8.0, compute values across a set of related rows without collapsing them. Every row keeps its identity and gains an extra column such as a rank, a running total or the previous row's value.

sql
function(...) OVER (
    [PARTITION BY columns]   -- split rows into independent windows
    [ORDER BY columns]       -- order rows inside each window
    [frame]                  -- optional: which rows around the current one
)

Aggregates as window functions

Any aggregate can be used with OVER. With an empty OVER () the window is the whole result; with PARTITION BY it is the row's group:

mysql · try it yourself
SELECT first_name, title, salary,
       SUM(salary) OVER () AS payroll,
       ROUND(AVG(salary) OVER (PARTITION BY title), 2) AS avg_for_title,
       salary - ROUND(AVG(salary) OVER (PARTITION BY title), 2) AS diff
FROM employees
WHERE title IN ('Sales Rep', 'Packer')
ORDER BY title, salary DESC;
+------------+-----------+---------+----------+---------------+---------+
| first_name | title     | salary  | payroll  | avg_for_title | diff    |
+------------+-----------+---------+----------+---------------+---------+
| Tom        | Packer    | 2900.00 | 16850.00 |       2825.00 |   75.00 |
| Sara       | Packer    | 2750.00 | 16850.00 |       2825.00 |  -75.00 |
| Linus      | Sales Rep | 3900.00 | 16850.00 |       3733.33 |  166.67 |
| Maya       | Sales Rep | 3700.00 | 16850.00 |       3733.33 |  -33.33 |
| Omar       | Sales Rep | 3600.00 | 16850.00 |       3733.33 | -133.33 |
+------------+-----------+---------+----------+---------------+---------+

With GROUP BY title you'd get two rows; here every employee is still listed, next to their group's numbers.

Ranking: ROW_NUMBER, RANK, DENSE_RANK

The ranking functions need an ORDER BY inside OVER. They differ only in how they treat ties:

Function Ties Example values
ROW_NUMBER() arbitrary but unique numbers 1, 2, 3, 4
RANK() same rank, then a gap 1, 2, 2, 4
DENSE_RANK() same rank, no gap 1, 2, 2, 3
mysql · try it yourself
SELECT name, unit_price,
       ROW_NUMBER() OVER (ORDER BY unit_price DESC, name) AS row_num,
       RANK()       OVER (ORDER BY ROUND(unit_price) DESC) AS rnk,
       DENSE_RANK() OVER (ORDER BY ROUND(unit_price) DESC) AS dense
FROM products
WHERE category_id IN (3, 5)
ORDER BY row_num;
+----------------------+------------+---------+-----+-------+
| name                 | unit_price | row_num | rnk | dense |
+----------------------+------------+---------+-----+-------+
| Aged Gruyere 250g    |       7.95 |       1 |   1 |     1 |
| Roasted Almonds 200g |       5.49 |       2 |   2 |     2 |
| Greek Yogurt 500g    |       3.95 |       3 |   3 |     3 |
| Salted Butter 250g   |       2.85 |       4 |   4 |     4 |
| Dark Chocolate Bar   |       2.49 |       5 |   5 |     5 |
| Sea Salt Crisps      |       1.99 |       6 |   5 |     5 |
| Whole Milk 1L        |       1.45 |       7 |   7 |     6 |
+----------------------+------------+---------+-----+-------+

Ranking by the rounded price makes some products tie, so you can see how RANK leaves a gap after a tie and DENSE_RANK doesn't.

Top N per group

A classic use: the most expensive product in each category. Rank inside each partition, then keep rank 1. Window functions can't appear in WHERE (they are computed after it), so the ranking goes in a derived table or CTE:

mysql · try it yourself
SELECT category_id, name, unit_price
FROM (
    SELECT category_id, name, unit_price,
           ROW_NUMBER() OVER (PARTITION BY category_id ORDER BY unit_price DESC) AS pos
    FROM products
) AS ranked
WHERE pos = 1
ORDER BY category_id;
+-------------+----------------------+------------+
| category_id | name                 | unit_price |
+-------------+----------------------+------------+
|           1 | Espresso Beans 1kg   |      24.50 |
|           2 | Chocolate Cake       |      18.00 |
|           3 | Aged Gruyere 250g    |       7.95 |
|           4 | Gala Apples 1kg      |       2.99 |
|           5 | Roasted Almonds 200g |       5.49 |
|           6 | Laundry Pods (30)    |      11.90 |
+-------------+----------------------+------------+

Running totals and moving averages

With ORDER BY in the window, an aggregate becomes cumulative: by default the frame runs from the first row up to the current one. An explicit frame like ROWS BETWEEN 2 PRECEDING AND CURRENT ROW gives a moving window:

mysql · try it yourself
SELECT month, revenue,
       SUM(revenue) OVER (ORDER BY month) AS running_total,
       ROUND(AVG(revenue) OVER (ORDER BY month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 2) AS avg_last_3
FROM (
    SELECT DATE_FORMAT(o.order_date, '%Y-%m') AS month,
           ROUND(SUM(d.quantity * d.unit_price * (1 - d.discount)), 2) AS revenue
    FROM orders AS o
    JOIN order_details AS d ON d.order_id = o.order_id
    WHERE o.status <> 'cancelled'
    GROUP BY month
) AS monthly
ORDER BY month;
+---------+---------+---------------+------------+
| month   | revenue | running_total | avg_last_3 |
+---------+---------+---------------+------------+
| 2025-01 |  139.87 |        139.87 |     139.87 |
| 2025-02 |   66.09 |        205.96 |     102.98 |
| 2025-03 |   96.98 |        302.94 |     100.98 |
| 2025-04 |   89.14 |        392.08 |      84.07 |
| 2025-05 |   82.85 |        474.93 |      89.66 |
| 2025-06 |   44.62 |        519.55 |      72.20 |
+---------+---------+---------------+------------+

The derived table first produces one row per month with GROUP BY; the window functions then run over those monthly rows. avg_last_3 is a three-month moving average: for the first two months there are fewer rows in the frame, so it averages what is there.

Note: With ORDER BY and no explicit frame, the default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which includes all rows that tie with the current one. For running totals over values that may repeat, write ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW (or order by a unique key) to add rows one at a time.

LAG and LEAD

LAG(expr) returns the value from the previous row of the window, LEAD(expr) from the next. They are perfect for "change since last time" questions, such as the days between a customer's orders:

mysql · try it yourself
SELECT customer_id, order_id, order_date,
       LAG(order_date) OVER w AS previous_order,
       DATEDIFF(order_date, LAG(order_date) OVER w) AS days_since_previous
FROM orders
WHERE customer_id IN (1, 2)
WINDOW w AS (PARTITION BY customer_id ORDER BY order_date)
ORDER BY customer_id, order_date;
+-------------+----------+------------+----------------+---------------------+
| customer_id | order_id | order_date | previous_order | days_since_previous |
+-------------+----------+------------+----------------+---------------------+
|           1 |        1 | 2025-01-05 | NULL           |                NULL |
|           1 |        4 | 2025-01-27 | 2025-01-05     |                  22 |
|           1 |       14 | 2025-04-08 | 2025-01-27     |                  71 |
|           2 |        2 | 2025-01-09 | NULL           |                NULL |
|           2 |        8 | 2025-02-22 | 2025-01-09     |                  44 |
|           2 |       19 | 2025-05-20 | 2025-02-22     |                  87 |
+-------------+----------+------------+----------------+---------------------+

The WINDOW w AS (...) clause names a window definition so that several functions can share it. The first order of each customer has no previous one, so LAG returns NULL (pass a default as the third argument: LAG(x, 1, 0)).

Other window functions

Function Returns
NTILE(n) splits the window into n roughly equal buckets (quartiles with n = 4)
FIRST_VALUE(x), LAST_VALUE(x), NTH_VALUE(x, n) a value from the first, last or n-th row of the frame
PERCENT_RANK(), CUME_DIST() relative rank between 0 and 1
mysql · try it yourself
SELECT first_name, salary,
       NTILE(3) OVER (ORDER BY salary DESC) AS pay_band,
       FIRST_VALUE(first_name) OVER (ORDER BY salary DESC) AS top_earner
FROM employees
ORDER BY salary DESC;
+------------+---------+----------+------------+
| first_name | salary  | pay_band | top_earner |
+------------+---------+----------+------------+
| Grace      | 9500.00 |        1 | Grace      |
| Alan       | 6200.00 |        1 | Grace      |
| Ada        | 5800.00 |        1 | Grace      |
| Linus      | 3900.00 |        2 | Grace      |
| Maya       | 3700.00 |        2 | Grace      |
| Omar       | 3600.00 |        2 | Grace      |
| Tom        | 2900.00 |        3 | Grace      |
| Sara       | 2750.00 |        3 | Grace      |
+------------+---------+----------+------------+

Test yourself

How do window functions differ from GROUP BY aggregates?

  1. They are faster
  2. They keep every row and add a computed column
  3. They only work on numbers
  4. They require a HAVING clause

Three rows tie for 2nd place. What rank does the next row get with RANK()?

  1. 3
  2. 4
  3. 5
  4. 2

Why can't you write WHERE ROW_NUMBER() OVER (...) = 1?

  1. ROW_NUMBER needs PARTITION BY
  2. Window functions are evaluated after WHERE
  3. WHERE can't contain functions
  4. It works fine