Window functions perform calculations across rows that are related to the current row โ without collapsing the result like GROUP BY.
1๏ธโฃ ROW_NUMBER() โ Assigns a unique row number per partition
SELECT name, department,
ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rank
FROM employees;
โค Gives ranking within each department
2๏ธโฃ RANK() & DENSE_RANK() โ Ranking with gaps (RANK) or without gaps (DENSE_RANK)
SELECT name, salary,
RANK() OVER (ORDER BY salary DESC) AS rank
FROM employees;
3๏ธโฃ LAG() & LEAD() โ Access previous or next row value
SELECT name, salary,
LAG(salary) OVER (ORDER BY salary) AS prev_salary,
LEAD(salary) OVER (ORDER BY salary) AS next_salary
FROM employees;
โค Compare salary trends row-wise
4๏ธโฃ SUM(), AVG(), COUNT() OVER() โ Running totals, moving averages, etc.
SELECT department, salary,
SUM(salary) OVER (PARTITION BY department) AS dept_total
FROM employees;
5๏ธโฃ NTILE(n) โ Divides rows into n equal buckets
SELECT name, salary,
NTILE(4) OVER (ORDER BY salary DESC) AS quartile
FROM employees;
๐ก Why Use Window Functions:
โข Perform row-wise calculations
โข Avoid GROUP BY limitations
โข Enable advanced analytics (ranking, trends, etc.)
๐งช Practice Task:
Write a query to find the top 2 earners in each department using ROW_NUMBER().
๐ฌ Tap โค๏ธ for more!