PostgreSQL Window Functions

Advanced window functions

ROW_NUMBER

SELECT name, ROW_NUMBER() OVER (ORDER BY salary DESC)
FROM employees; # sequential row number

RANK

SELECT name, RANK() OVER (ORDER BY score DESC)
FROM students; # rank with gaps

DENSE_RANK

SELECT name, DENSE_RANK() OVER (ORDER BY score DESC)
FROM students; # rank without gaps

PARTITION BY

SELECT department, name,
    RANK() OVER (PARTITION BY department ORDER BY salary DESC)
FROM employees; # rank within groups

LAG and LEAD

SELECT date, sales,
    LAG(sales) OVER (ORDER BY date) AS prev_sales
FROM daily_sales; # previous row value
SELECT LEAD(sales) OVER (ORDER BY date); # next row value

Aggregate Windows

SELECT date, sales,
    SUM(sales) OVER (ORDER BY date) AS running_total
FROM sales; # running sum