Window functions in SQL provide the ability to perform calculations on a set of rows related to the current row. Unlike aggregate functions, which return a single value for each group, window functions return a single value for each row based on the rows in its "window". This allows for more advanced calculations and rankings without collapsing multiple rows into a single output row.
The primary components of a window function are:
SELECT
EmployeeName,
Department,
Salary,
ROW_NUMBER() OVER (ORDER BY Salary DESC) AS 'Rank'
FROM Employees;
This example assigns a unique rank to each employee based on their salary in descending order.
SELECT
EmployeeName,
Department,
Salary,
RANK() OVER (ORDER BY Salary DESC) AS 'Rank',
DENSE_RANK() OVER (ORDER BY Salary DESC) AS 'DenseRank'
FROM Employees;
In this example, RANK() provides a unique rank for each salary but leaves gaps in ranking for equal salary values. DENSE_RANK(), on the other hand, does not leave gaps.
SELECT
EmployeeName,
Salary,
LAG(Salary, 1) OVER (ORDER BY Salary) AS 'PreviousSalary',
LEAD(Salary, 1) OVER (ORDER BY Salary) AS 'NextSalary'
FROM Employees;
LAG() returns the previous row's salary, and LEAD() returns the next row's salary.
SELECT
EmployeeName,
Salary,
SUM(Salary) OVER (ORDER BY EmployeeName) AS 'CumulativeSalary'
FROM Employees;
This example calculates a running total of salaries, ordered by employee names.
Window functions bring a powerful dimension to SQL querying, allowing for more complex analyses on datasets without the need to aggregate or transform the data in cumbersome ways. By understanding and leveraging window functions, developers can achieve a deeper insight into their data and produce more efficient and effective queries.