What are window functions in SQL
· Category: SQL & Databases
Short answer
Window functions compute values across a set of rows related to the current row, defined by an OVER clause, without collapsing the result set like GROUP BY.
Steps
- Rank rows:
SELECT name, salary, RANK() OVER (ORDER BY salary DESC) FROM employees; - Partition by group:
SELECT name, department, salary, AVG(salary) OVER (PARTITION BY department) FROM employees; - Running total:
SELECT date, amount, SUM(amount) OVER (ORDER BY date) AS running_total FROM transactions; - Frame specifications:
ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING - Common functions:
ROW_NUMBER(),RANK(),DENSE_RANK(),LEAD(),LAG(),NTILE()
Tips
- Window functions can appear in
SELECTandORDER BYbut not inWHERE. - Combine multiple window definitions with named windows using the
WINDOWclause.
Common issues
- Forgetting
OVER()turns a window function into an ordinary aggregate, causing syntax errors. RANK()leaves gaps after ties; useDENSE_RANK()for continuous ranking.r