Sitemap
Rakesh M

Rakesh M

SQL Window function

5 min readMar 4, 2024
Press enter or click to view image in full size
Window function in SQL

What if I told you there is a function in SQL that can seamlessly solve most analytical problems?

What if I told you that you can partition the database into segments and then amalgamate those segments to retrieve the desired results using window functions?

The window function is one of the most useful and must-learn functions if you want to make your SQL journey easier.

Before starting with SQL function we know what is over( ), partition by ( ),

and order by( ),

Sure, let’s break it down in simpler terms:

1. OVER(): Imagine you have a big stack of papers with information written on each page. The `OVER()` part is like putting a window or a frame around a specific section of those papers. It tells the computer, “Hey, only pay attention to the information inside this window.”

2. PARTITION BY ( ): Now, let’s say your papers are about different departments in a company. Using `PARTITION BY` is like putting dividers between papers belonging to different departments. It tells the computer, “Okay, let’s group these papers together based on the department they belong to.”

3. ORDER BY ( ): Finally, let’s say you want to organize the papers within each department by date, from oldest to newest. That’s where `ORDER BY` comes in. It tells the computer, “Alright, let’s arrange these papers in a specific order so we can work with them more easily.”

Putting it all together, if you say something like “Find the average salary for each department, ordered by employee name,” you’re essentially telling the computer to look at each department separately (`PARTITION BY`), arrange the employees within each department by name (`ORDER BY`), and then calculate the average salary (`OVER()`) for each group of employees in their respective departments.

There are many window functions, but we will be learning some important ones:

  1. Row_number
  2. Rank
  3. Dense Rank
  4. Lead and Lag

Row_number ( ): As the name suggests, it displays row numbers for each row, starting from 1 onwards.

Usage: Let’s take our favorite example, “The Employee Table.” I’m sure everyone who has started their journey in SQL has definitely come across the Employee Table.

Get Rakesh M’s stories in your inbox

Join Medium for free to get updates from this writer.

We will be using this Employee table for all our example to grasp the knowledge of window functions.

Employee Table

Consider an Employee table with columns: emp_ID, emp_name, Dept_name, and Salary. To assign a unique row number to each employee within each department based on their salary in ascending order, you can use the following query:

SELECT emp_ID, emp_name, Dept_name, Salary,
ROW_NUMBER() OVER (PARTITION BY Dept_name ORDER BY emp_ID) AS rn
FROM Employee;

This query will generate a result set with the columns emp_ID, emp_name, Dept_name, Salary, and rn, where rn represents the row number within each department.

Row_number query result.

Rank ( ): In a typical Indian family, the first question a relative often asks about our parents is, “What rank is your son?” I believe you are imagining that one relative who always asks that one question all the time. Lets answer that using an SQL window function with little changes which everybody can remember.

Lets go back to our favorite Employee Table, Now, let’s consider that we are grown-up kids. The relative’s question changes from “What rank is your son?” to “What is your son’s salary?”

Now we can see an example where we rank the employees based on salary.

SELECT emp_ID, emp_name, Dept_name, Salary,
RANK() OVER (PARTITION BY Dept_name ORDER BY Salary desc) AS rnk
FROM Employee;
Rank ( ) query result.

We have a major difference between Rank() and Dense_rank(). We will cover it once we finish Dense_rank(), so we will understand the difference.

Dense_rank ( ): It is a window function in SQL that assigns a unique, consecutive rank to each distinct row within a partition of a result set, without any gaps. It is similar to the Rank() function, but it does not leave gaps in the ranking sequence when there are ties, in Rank( ) if there are consecutive rank it will skip a Rank( ) whereas in Dense_rank( ) it won’t.

Lets Understand it with an example with Employee table

SELECT emp_ID, emp_name, Dept_name, Salary,
RANK() OVER (PARTITION BY Dept_name ORDER BY Salary desc) AS rnk
DENSE_RANK() OVER (PARTITION BY Dept_name ORDER BY Salary desc) AS dense_rnk
FROM Employee;
Rank and Dense Rank query result.

From the above example we are able to understand and see the difference between Rank( ) and Dense_rank( ).

Lead and Lag: As the name suggests, Lead fetches the next values, whereas Lag fetches the preceding value.

There is nothing much to explain about this tow windows function we will understand it by a example.

SELECT emp_ID, emp_name, Dept_name, Salary,
lag() OVER (PARTITION BY Dept_name ORDER BY emp_ID) AS prev_emp_salary
lead() OVER (PARTITION BY Dept_name ORDER BY emp_ID) AS next_emp_salary
FROM Employee;
Press enter or click to view image in full size
Lead and Lag Query Result.

Note: You will be having the doubt why there is “NULL” at the beginning of the lag( ) function and at the “NULL” at the end of lead( ) function, it is because for the lag( ) function there is no more preceding values before that so there is no value to compare with, same goes for Lead( ) as well there is no next values to compare the salary with.

Hope I was able to make you understand you about some of the important SQL concepts, lets meet at next blog :)

Happy Learning!!

--

--