Windows Function SQL
Windows Function SQL
Window functions apply aggregate and ranking functions over a particular window (set of
rows). OVER clause is used with window functions to define that window. OVER clause does
two important things:
Basic Syntax :
SELECT coulmn_name1,
window_function(cloumn_name2),
OVER([PARTITION BY column_name1] [ORDER BY column_name3]) AS new_column
FROM table_name;
1
Proprietary content. © 2013 - 2021 Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.
Consider the following employee table :
Example:
Find the average salary of employees for each department and order employees within a
department by age.
SELECT *, AVG(Salary) OVER(PARTITION BY Department ORDER BY age) FROM employee;
DENSE_RANK() :
It assigns rank to each row within the partition. Just like the rank function, the first row is
assigned rank 1 and rows having the same value have the same rank. The difference between
RANK() and DENSE_RANK() is that in DENSE_RANK(), for the next rank after two of the same
rank, consecutive integers are used, no rank is skipped.
Example:
Find the rank of employees based on highest salary to lowest salary for each department
2
Proprietary content. © 2013 - 2021 Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.
SELECT *, DENSE_RANK() OVER(ORDER BY Salary DESC) FROM employee;
ROW_NUMBER() :
It assigns consecutive integers to all the rows within the partition. Within a partition, no two
rows can have the same row number.
Example:
Add column row number to the table
SELECT *, ROW_NUMBER() OVER(ORDER BY Salary DESC) FROM employee;
LAG() :
The LAG() function allows access to a value stored in a different row above the current row. The
row above may be adjacent or some number of rows above, as sorted by a specified column or
set of columns.
LEAD() :
LEAD() is similar to LAG(). Whereas LAG() accesses a value stored in a row above, LEAD()
accesses a value stored in a row below.
NTILE() :
The MySQL NTILE() function divides rows in a sorted partition into a specific number of groups.
Each group is assigned a bucket number starting at one. For each row, the NTILE() function
returns a bucket number representing the group to which the row belongs.
3
Proprietary content. © 2013 - 2021 Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.
DENSE_RANK() DENSE_RANK() OVER (PARTITION BY column_name
ORDER BY column_name)
4
Proprietary content. © 2013 - 2021 Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.
5
Proprietary content. © 2013 - 2021 Great Learning. All Rights Reserved. Unauthorized use or distribution prohibited.