SQL Window Functions are a feature in SQL that allow you to perform calculations across a set of table rows that are somehow related to the current row.

Unlike regular aggregate functions, which return a single value for a group of rows, window functions return a value for each row in the result set while still allowing access to the individual row data.

Key Characteristics of Window Functions

  1. Non-Aggregating: Window functions do not collapse rows into a single output row. Instead, they perform calculations across a defined “window” of rows related to the current row.

  2. OVER Clause: Window functions are defined using the OVER clause, which specifies the window of rows to be considered for the function.

  3. Partitioning: You can partition the result set into groups using the PARTITION BY clause within the OVER clause. Each partition is processed independently.

  4. Ordering: You can specify the order of rows within each partition using the ORDER BY clause within the OVER clause.

Example Use Case

Suppose you have a table sales with columns salesperson, region, and amount. You can use window functions to calculate the total sales for each salesperson while still displaying individual sales records:

Initial Table: employees

idnamedepartmentsalary
1AliceSales50000
2BobSales60000
3CharlieHR55000
4DavidHR70000
5EveIT80000
6FrankIT75000

Example Queries Using SQL Window Functions

1. Using ROW_NUMBER()

The ROW_NUMBER() function assigns a unique rank to each employee within their department based on their salary.

SELECT 
    id, 
    name, 
    department, 
    salary, 
    ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rank
FROM employees;

Resulting Table:

idnamedepartmentsalaryrank
2BobSales600001
1AliceSales500002
4DavidHR700001
3CharlieHR550002
5EveIT800001
6FrankIT750002

2. Using SUM() similar AVG

The SUM() function calculates the total salary for each department, showing the same total for each employee in that department.

SELECT 
    id, 
    name, 
    department, 
    salary, 
    SUM(salary) OVER (PARTITION BY department) AS total_department_salary
FROM employees;

Resulting Table:

idnamedepartmentsalarytotal_department_salary
1AliceSales50000110000
2BobSales60000110000
3CharlieHR55000125000
4DavidHR70000125000
5EveIT80000155000
6FrankIT75000155000

SQL Window functions Tags:data_analysis,querying