Window Functions in SQL
From the SQL cheat sheet ยท Window Functions ยท verified Jul 2026
Window Functions
ROW_NUMBER, RANK, LAG, LEAD, running totals, and partitioned aggregates.
sql
-- ROW_NUMBER
SELECT name, salary,
ROW_NUMBER() OVER (ORDER BY salary DESC) AS rank
FROM employees;
-- RANK with PARTITION BY
SELECT name, department, salary,
RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS dept_rank
FROM employees;
-- Running total
SELECT date, amount,
SUM(amount) OVER (ORDER BY date) AS running_total
FROM payments;๐ก Window functions compute across rows without collapsing them โ unlike GROUP BY
โก ROW_NUMBER + CTE is the standard pattern for "top N per group" queries
๐ RANK has gaps after ties (1,2,2,4); DENSE_RANK has no gaps (1,2,2,3)
๐ข LAG/LEAD let you compare each row to its previous/next row โ great for trend analysis
windowrow-numberranklaglead