Saturday, July 19, 2025

Top 10 SQL Queries from Technical Interviews to Learn Window Functions like ROW_NUMBER

Hello guys, If you're preparing for SQL interviews or working on real-world reporting tasks, mastering window functions is no longer optional. They are one of the most powerful tools in SQL which allows you to perform calculations across rows related to the current row without collapsing your result set like GROUP BY does. Window functions like ROW_NUMBER(), RANK(), LEAD(), LAG(), and SUM() OVER help you write cleaner, faster, and more expressive queries—ideal for performance tuning and analytical processing.

Let’s dive into the Top 10 SQL window function queries that you must know.

10 SQL Query to Learn Window functions like Rank, Row_Number

Window functions are tough but very important tool and then can be used to solve a range of problems like top N results, de-duplication etc. Let's see popular SQL queries from Interviews to learn and Master window function. 

1. Write an SQL Query to Find the Row Number for Each Employee in a Department?

This is the simplest example of window function, ROW_NUMBER which can be used to assign each row a row_number. This is the basic technique we are going to solve many complex problem with ranking

SELECT EmpID, EmpName, DeptID, 

ROW_NUMBER() OVER (PARTITION BY DeptID ORDER BY Salary DESC) AS RowNum

FROM Employees;

What it teaches: 

ROW_NUMBER() assigns a unique number to rows within a partition. Helpful for pagination or top-N per group.


2. Write SQL Query to Rank Employees Based on Salary Within Department

If you have been giving interviews then you may have seen this problem below, we can use rank() to solve this problem. Rank handles ties by giving same rank and there will be break between ranks. 

SELECT EmpID, EmpName, DeptID,   
      RANK() OVER (PARTITION BY DeptID ORDER BY Salary DESC) AS SalaryRank

FROM Employees;

You can see that RANK() gives equal ranks for ties but skips subsequent numbers.


3. Write SQL query to Find the Running Total of Salaries in Each Department

This is another popular SQL interview question which can be solved using window functions as shown below:

SELECT EmpName, DeptID, Salary,  

SUM(Salary) OVER (PARTITION BY DeptID ORDER BY EmpID) AS RunningTotal

FROM Employees;

If you don't know you can also calculate running totals without subqueries using SUM() OVER.


4. Compare Salary with Previous Employee in Same Department

You can solve this problem by using lag() window function as shown below:

SELECT EmpID, EmpName, Salary,     
       LAG(Salary) OVER (PARTITION BY DeptID ORDER BY Salary) AS PrevSalary
FROM Employees;

The key thing you can learn from this example is that LAG() looks at the previous row’s value—used for comparisons or deltas.


5. Compare Salary with Next Employee in Same Department

This is another classic problem from interview, you can use lead() window function to solve it:

SELECT EmpID, EmpName, Salary,   
       LEAD(Salary) OVER (PARTITION BY DeptID ORDER BY Salary) AS NextSalary 
FROM Employees;


Another lesson here is that LEAD()  window function fetches value from the next row—handy in time series analysis.


6. Write a Query to get Top 2 Paid Employees Per Department

This is a classic top N problems you can solve using Window functions. 

SELECT * FROM (

  SELECT EmpID, EmpName, DeptID, Salary,

         ROW_NUMBER() OVER (PARTITION BY DeptID ORDER BY Salary DESC) AS rn

  FROM Employees

) AS ranked

WHERE rn <= 2;


In short, you can use Subquery + ROW_NUMBER() to fetch N records per group.


7. Write SQL query to Calculate Average Salary Over Department

You can use AVG() function over a window, which is a department in our case to calculate the average salary for each department

SELECT EmpID, EmpName, DeptID, Salary,

       AVG(Salary) OVER (PARTITION BY DeptID) AS AvgDeptSalary

FROM Employees;


This example also teaches you one very important lesson that you can aggregate stats without grouping data. You can see that we have not used group by clause, we have only partition data on windows. 


8. Count Employees with Salary More Than Department Average

This is another classic interview problem you will frequently see on interviews. You can solve this easily using window function by partitioning data by department. 

SELECT * FROM (

  SELECT EmpID, EmpName, DeptID, Salary,

         AVG(Salary) OVER (PARTITION BY DeptID) AS AvgDeptSalary

  FROM Employees

) AS sub

WHERE Salary > AvgDeptSalary;


The lesson here is that you can use filter using window aggregate comparison.


9. Write SQL query to find Time Difference Between Logins of Same User

Here is how you can solve this problem by using lag() and datediff() function

SELECT UserID, LoginTime,

       LAG(LoginTime) OVER (PARTITION BY UserID ORDER BY LoginTime) AS PrevLogin,

       DATEDIFF(MINUTE, LAG(LoginTime) OVER (PARTITION BY UserID 
       ORDER BY LoginTime), LoginTime) AS TimeGap

FROM Logins;

In short you can use LAG() + DATEDIFF() for session time analysis.


10. Calculate Percentage Contribution of Employee Salary in Department

This the last query in this article, try to solve yourself before looking at the solution

SELECT EmpID, EmpName, DeptID, Salary,

       ROUND(100.0 * Salary / SUM(Salary) OVER (PARTITION BY DeptID), 2) AS PercentShare

FROM Employees;

This query teaches us that window aggregates can be used for calculating ratios or percentages.


Here is also a nice infographic to revise and remember these queries and most importantly the lessons you learned


Top 10 SQL Queries from Technical Interviews to Master Window Functions



Conclusion

That's all about these top 10 SQL queries from Interviews to learn and master Window functions. These SQL queries are must-haves in your toolbelt—whether you're preparing for interviews at product companies or tackling real-world reporting dashboards.

Window functions are extremely common in advanced data analysis, and they replace messy subqueries with elegant, readable code.

If you're serious about becoming a data-savvy software engineer, go beyond basic SELECT queries. Practice, play, and explore window functions!

Other Interview Questions posts you may like Blog

Have any more SQL query doubts or need practice sets? Drop a comment below or share this post with your fellow devs 


    No comments :

    Post a Comment