📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials MySQL MySQL Window Functions

MySQL Window Functions

5 min read Quiz at the end
Window functions (ROW_NUMBER, RANK, LAG, LEAD, SUM OVER) for rankings and running totals.

Window Functions (MySQL 8.0+)

-- ROW_NUMBER
SELECT name, salary,
    ROW_NUMBER() OVER (ORDER BY salary DESC) AS rank_num
FROM employees;

-- RANK (ties get same rank, next rank skips)
SELECT name, dept, salary,
    RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS dept_rank
FROM employees;

-- DENSE_RANK (ties get same rank, no skipping)
SELECT name, DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_rank
FROM employees;

-- LAG and LEAD
SELECT name, salary,
    LAG(salary, 1)  OVER (ORDER BY hire_date) AS prev_salary,
    LEAD(salary, 1) OVER (ORDER BY hire_date) AS next_salary
FROM employees;

-- Running total
SELECT name, amount,
    SUM(amount) OVER (ORDER BY created_at) AS running_total
FROM payments;
Topic Quiz · 1 questions

Test your understanding before moving on

1. What does ROW_NUMBER() OVER (ORDER BY salary DESC) return?
💡 ROW_NUMBER assigns a unique sequential integer to each row in the ordered result set.