The Wayback Machine - https://web.archive.org/web/20250108180905/https://www.geeksforgeeks.org/window-functions-in-sql/
Open In App

Window Functions in SQL

Last Updated : 20 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

SQL window functions are an essential tool for database management and data analysis. They allow users to perform advanced calculations across a specified set of rows known as a “window” while retaining the individual data rows.

Unlike traditional aggregate functions that return a single result for an entire group, window functions provide calculations across different partitions or groups of data, enabling complex analysis without altering the original dataset.

In this article, we will cover everything we need to know about SQL window functions, including the OVER clause, partitioning, ordering, and common use cases.

What is a Window Function in SQL?

A window function in SQL is a type of function that allows us to perform calculations across a specific set of rows related to the current row. These calculations happen within a defined window of data, and they are particularly useful for aggregates, rankings, and cumulative totals without altering the dataset.

The OVER clause is key to defining this window. It partitions the data into different sets (using the PARTITION BY clause) and orders them (using the ORDER BY clause). These windows enable functions like SUM(), AVG(), ROW_NUMBER(), RANK(), and DENSE_RANK() to be applied in a sophisticated manner.

Syntax 

SELECT column_name1, 
window_function(column_name2)
OVER([PARTITION BY column_name1] [ORDER BY column_name3]) AS new_column
FROM table_name;

Key Terms

  • window_function= any aggregate or ranking function
  • column_name1= column to be selected
  • column_name2= column on which window function is to be applied
  • column_name3= column on whose basis partition of rows is to be done
  • new_column= Name of new column
  • table_name= Name of table

Types of Window Functions in SQL

SQL window functions can be categorized into two primary types: aggregate window functions and ranking window functions. These two types serve different purposes but share a common ability to perform calculations over a defined set of rows while retaining the original data.

1. Aggregate Window Function

These functions allow us to perform aggregate operations across a set of rows within the defined window, while still retaining the detail-level data.

Common Aggregate Window Functions include:

  • SUM()
  • AVG()
  • COUNT()
  • MAX()
  • MIN()

Example of Aggregate Window Function:

Consider an employee table with the following columns: Name, Age, Department, and Salary.

Name Age Department Salary
Ramesh 20 Finance 50, 000
Deep 25 Sales 30, 000
Suresh 22 Finance 50000
Ram 28 Finance 20, 000
Pradeep 22 Sales 20, 000

Query:

SELECT Name, Age, Department, Salary, 
AVG(Salary) OVER( PARTITION BY Department) AS Avg_Salary
FROM employee

Output

Name Age Department Salary Avg_Salary
Ramesh 20 Finance 50,000 40,000
Suresh 22 Finance 50,000 40,000
Ram 28 Finance 20,000 40,000
Deep 25 Sales 30,000 25,000
Pradeep 22 Sales 20,000 25,000

Explanation:

As shown, the average salary within each department remains constant for all rows in the department.

2. Ranking Window Functions

These functions provide rankings of rows within a partition based on specific criteria. Common ranking functions include:

  • RANK() –  As the name suggests, the rank function assigns rank to all the rows within every partition. Rank is assigned such that rank 1 given to the first row and rows having same value are assigned same rank. For the next rank after two same rank values, one rank value will be skipped. For instance, if two rows share­ rank 1, the next row gets rank 3, not 2.
     
  • DENSE_RANK() – It assigns rank to each row within partition. Just like rank function first row is assigned rank 1 and rows having same value have same rank. The difference between RANK() and DENSE_RANK() is that in DENSE_RANK(), for the next rank after two same rank, consecutive integer is used, no rank is skipped. 
     
  • ROW_NUMBER() – ROW_NUMBER() gives e­ach row a unique number. It numbers rows from one­ to the total rows. The rows are put into groups base­d on their values. Each group is called a partition. In e­ach partition, rows get numbers one afte­r another. No two rows have the same­ number in a partition.

Example of Ranking Window Functions

To calculate the rank, dense rank, and row number of employees within each department based on salary, use the following query:

Query: 

SELECT 
ROW_NUMBER() OVER (PARTITION BY Department ORDER BY Salary DESC) AS emp_row_no,
Name,
Department,
Salary,
RANK() OVER(PARTITION BY Department ORDER BY Salary DESC) AS emp_rank,
DENSE_RANK() OVER(PARTITION BY Department ORDER BY Salary DESC) AS emp_dense_rank
FROM
employee;

Output

emp_row_no Name Department Salary emp_rank emp_dense_rank
1 Ramesh Finance 50, 000 1 1
2 Suresh Finance 50, 000 1 1
3 Ram Finance 20, 000 3 2
1 Deep Sales 30, 000 1 1
2 Pradeep Sales 20, 000 2 2

Explanation:

So, we can see that as mentioned in the definition of ROW_NUMBER() the row numbers are consecutive integers within each partition. Also, we can see difference between rank and dense rank that in dense rank there is no gap between rank values while there is gap in rank values after repeated rank. 

Conclusion

SQL window functions are a crucial feature for advanced data analysis and provide flexibility when working with partitioned data. By mastering the OVER clause, PARTITION BY, and ORDER BY, we can perform complex calculations like aggregate calculations, ranking, and cumulative totals while preserving the row-level data.

Using these window functions SQL features, we can perform advanced data analysis tasks with ease. The combination of window functions with ORDER BY and PARTITION BY provides a flexible approach for data manipulation across different types of datasets.

FAQs

What is a window function in SQL?

A window function in SQL performs a calculation across a set of table rows related to the current row within a specified window. Unlike regular aggregate functions, window functions allow you to retain individual rows while performing the calculation.

What is the window function OVER in SQL?

The OVER clause in SQL defines the window or range of rows the window function should operate on. It is used with functions like ROW_NUMBER(), RANK(), or SUM() to calculate values across a partition of the result set.

What is the window function SQL LAST?

The LAST_VALUE() function in SQL is a window function that returns the last value in a specified window of rows. It allows you to retrieve the last value within a partition, ordered according to the given sorting criteria.



Next Article
Article Tags :

Similar Reads

three90RightbarBannerImg