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;