Window functions calculate across related rows without collapsing them into one. ROW_NUMBER(), RANK(), LAG(), LEAD(), and running SUM() OVER() are common. They are essential for rankings and period comparisons.
Window Functions
-- Rank users by total spending
SELECT name, total,
RANK() OVER (ORDER BY total DESC) AS rank
FROM orders;
-- Running total
SELECT date, total,
SUM(total) OVER (ORDER BY date) AS running_total
FROM orders;
-- Row number per partition
SELECT city, name,
ROW_NUMBER() OVER (PARTITION BY city ORDER BY name) AS rn
FROM users;