The window frame in SQL window functions is a critical feature that defines a specific subset of rows within a partition for the function to evaluate. This subset is specified using the ROWS or RANGE clauses within the OVER() function. The window frame determines the precise range of rows over which the window function will perform its calculation, allowing for more granular and contextually relevant analysis.
window_function() OVER (PARTITION BY column_name ORDER BY column_name
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
SELECT employee_id,
salary,
SUM(salary) OVER (PARTITION BY department_id
ORDER BY salary
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total
FROM employees;
SELECT employee_id,
salary,
SUM(salary) OVER (PARTITION BY department_id
ORDER BY salary
RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) AS range_total
FROM employees;