The OVER() clause is the cornerstone of SQL window functions, defining the window or subset of rows over which the function is applied. This clause allows for partitioning and ordering the data within the window, essential for accurate calculations and analysis.
SELECT column_name,
window_function() OVER (PARTITION BY column_name ORDER BY column_name)
FROM table_name;
OVER()SUM(), AVG(), ROW_NUMBER()).SELECT employee_id,
salary,
AVG(salary) OVER (ORDER BY salary) AS running_avg_salary
FROM employees;
This query calculates a running average of salaries, ordered by the salary column.
The PARTITION BY clause within the OVER() function is used to segment the result set into distinct partitions. Each partition is treated separately, allowing window functions to perform calculations independently for each group.
SELECT column_name,
window_function() OVER (PARTITION BY column_name)
FROM table_name;
SELECT department_id,
employee_id,
salary,
AVG(salary) OVER (PARTITION BY department_id) AS avg_dept_salary
FROM employees;
This query calculates the average salary for each department.