MySQL 8 Window Functions: ROW_NUMBER, RANK, LAG and Running Totals

MySQL 65 min min read Updated: Nov 27, 2026 Intermediate
MySQL 8 Window Functions: ROW_NUMBER, RANK, LAG and Running Totals
Intermediate Topic 2 of 3
Version note Window functions arrived in MySQL 8.0. MySQL 5.7 does not have them, so people used user variables or self joins. Everything here needs 8.0 or later.

The Idea

An aggregate with GROUP BY collapses rows. A window function keeps every row and adds a calculated column. OVER (...) defines the window.

sql SELECT name, category, price, ROUND(AVG(price) OVER (PARTITION BY category), 2) AS category_avg FROM products ORDER BY category, name;

Result:

namecategorypricecategory_avg
HeadphonesElectronics79.00525.67
LaptopElectronics899.00525.67
PhoneElectronics599.00525.67
ChairFurniture129.00141.00
DeskFurniture249.00141.00
LampFurniture45.00141.00
NotebookStationery3.504.25
Pen PackStationery5.004.25

Ranking

sql SELECT name, category, price, ROW_NUMBER() OVER (PARTITION BY category ORDER BY price DESC) AS rn, RANK() OVER (PARTITION BY category ORDER BY price DESC) AS rnk, DENSE_RANK() OVER (PARTITION BY category ORDER BY price DESC) AS drnk FROM products ORDER BY category, price DESC;

Result:

namecategorypricernrnkdrnk
LaptopElectronics899.00111
PhoneElectronics599.00222
HeadphonesElectronics79.00333
DeskFurniture249.00111
ChairFurniture129.00222
LampFurniture45.00333
Pen PackStationery5.00111
NotebookStationery3.50222

With ties, ROW_NUMBER still gives different numbers, RANK leaves gaps (1, 1, 3), and DENSE_RANK does not (1, 1, 2). Try it with tied values:

sql CREATE TABLE scores (name VARCHAR(10), pts INT); INSERT INTO scores VALUES ('A', 90), ('B', 90), ('C', 80), ('D', 70); SELECT name, pts, ROW_NUMBER() OVER (ORDER BY pts DESC, name) AS rn, RANK() OVER (ORDER BY pts DESC) AS rnk, DENSE_RANK() OVER (ORDER BY pts DESC) AS drnk FROM scores ORDER BY pts DESC, name;

Result:

nameptsrnrnkdrnk
A90111
B90211
C80332
D70443

Top N per Group

A window function cannot be used in WHERE, so wrap it in a derived table or CTE:

sql SELECT category, name, price FROM ( SELECT category, name, price, ROW_NUMBER() OVER (PARTITION BY category ORDER BY price DESC) AS rn FROM products ) t WHERE rn <= 2 ORDER BY category, price DESC;

Result:

categorynameprice
ElectronicsLaptop899.00
ElectronicsPhone599.00
FurnitureDesk249.00
FurnitureChair129.00
StationeryPen Pack5.00
StationeryNotebook3.50

Running Totals and Moving Averages

sql SELECT id, order_date, status, COUNT(*) OVER (ORDER BY order_date, id) AS orders_so_far FROM orders ORDER BY order_date, id;

Result:

idorder_datestatusorders_so_far
12025-01-10shipped1
22025-02-14shipped2
32025-02-20shipped3
42025-03-01pending4
52025-03-15cancelled5
62025-04-02shipped6
72025-04-20pending7
82025-05-05shipped8
92025-05-11shipped9
102025-06-01shipped10

Running revenue needs the order totals. Aggregate first, then window over the result:

sql WITH daily AS ( SELECT o.order_date, SUM(oi.quantity * p.price) AS revenue FROM orders o JOIN order_items oi ON oi.order_id = o.id JOIN products p ON p.id = oi.product_id WHERE o.status <> 'cancelled' GROUP BY o.order_date ) SELECT order_date, ROUND(revenue, 2) AS revenue, ROUND(SUM(revenue) OVER (ORDER BY order_date), 2) AS running_revenue FROM daily ORDER BY order_date;

Result:

order_daterevenuerunning_revenue
2025-01-101057.001057.00
2025-02-1455.001112.00
2025-02-20599.001711.00
2025-03-01507.002218.00
2025-04-02989.003207.00
2025-04-20237.003444.00
2025-05-05199.003643.00
2025-05-11678.004321.00
2025-06-0160.004381.00

LAG and LEAD: Compare with a Neighbour

sql WITH daily AS ( SELECT o.order_date, SUM(oi.quantity * p.price) AS revenue FROM orders o JOIN order_items oi ON oi.order_id = o.id JOIN products p ON p.id = oi.product_id WHERE o.status <> 'cancelled' GROUP BY o.order_date ) SELECT order_date, ROUND(revenue, 2) AS revenue, ROUND(LAG(revenue) OVER (ORDER BY order_date), 2) AS previous, ROUND(revenue - LAG(revenue, 1, 0) OVER (ORDER BY order_date), 2) AS diff FROM daily ORDER BY order_date;

Result:

order_daterevenuepreviousdiff
2025-01-101057.00NULL1057.00
2025-02-1455.001057.00-1002.00
2025-02-20599.0055.00544.00
2025-03-01507.00599.00-92.00
2025-04-02989.00507.00482.00
2025-04-20237.00989.00-752.00
2025-05-05199.00237.00-38.00
2025-05-11678.00199.00479.00
2025-06-0160.00678.00-618.00

LAG(x, 1, 0) looks one row back and uses 0 when there is no earlier row. LEAD looks forward.

Frames: Moving Windows

sql WITH daily AS ( SELECT o.order_date, SUM(oi.quantity * p.price) AS revenue FROM orders o JOIN order_items oi ON oi.order_id = o.id JOIN products p ON p.id = oi.product_id WHERE o.status <> 'cancelled' GROUP BY o.order_date ) SELECT order_date, ROUND(revenue, 2) AS revenue, ROUND(AVG(revenue) OVER (ORDER BY order_date ROWS BETWEEN 1 PRECEDING AND CURRENT ROW), 2) AS avg_last_two FROM daily ORDER BY order_date;

Result:

order_daterevenueavg_last_two
2025-01-101057.001057.00
2025-02-1455.00556.00
2025-02-20599.00327.00
2025-03-01507.00553.00
2025-04-02989.00748.00
2025-04-20237.00613.00
2025-05-05199.00218.00
2025-05-11678.00438.50
2025-06-0160.00369.00

NTILE, FIRST_VALUE and Named Windows

sql SELECT name, price, NTILE(2) OVER w AS half, FIRST_VALUE(name) OVER w AS cheapest_name FROM products WINDOW w AS (ORDER BY price) ORDER BY price;

Result:

namepricehalfcheapest_name
Notebook3.501Notebook
Pen Pack5.001Notebook
Lamp45.001Notebook
Headphones79.001Notebook
Chair129.002Notebook
Desk249.002Notebook
Phone599.002Notebook
Laptop899.002Notebook

WINDOW w AS (...) names a window so you can reuse it.

Frame default surprise With ORDER BY and no frame, the default frame runs to the current row including ties, so LAST_VALUE often returns the current row. Write the frame explicitly: ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING.

Common Beginner Mistakes

MistakeWhat happensFix
Window function in WHEREErrorWrap in a CTE or derived table
Using RANK for top 1Ties return many rowsUse ROW_NUMBER with a tie-breaker
No tie-breaker in ORDER BYUnstable numbersAdd a unique column
Using these on MySQL 5.7Syntax errorUpgrade to 8.0
AS rankReserved word errorPick another alias

Practice

  1. Rank customers by total spend.
  2. Find each customer's most recent order with ROW_NUMBER.
  3. Show days between a customer's orders with LAG.
  4. Compute a 3-row moving average.

Conclusion

Window functions add a calculation per row with OVER. Use PARTITION BY for groups, ORDER BY for sequence, ROW_NUMBER/RANK for ranking, LAG/LEAD for neighbours and frames for moving totals.

Quick Summary: OVER, PARTITION BY, ROW_NUMBER, RANK, LAG, LEAD, running total, frames, WINDOW.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators