sql query to find second largest salary dens_rank
#sql-query-to-find-second-largest-salary #largest-salary #sql-query #sql #Article
This is Question is most use full in Sql interview ,Below is Employee Table and we are going to write Sql Query using Dense rank function that is windowing function :
Let’s consider an Employee table with the following data:
Name | Age | Salary | Department |
---|---|---|---|
Shubham Mishra | 31 | 20000 | Computer |
Rahul Kumar | 20 | 30000 | Electric |
Our goal is to find the second highest salary in this table.
DENSE_RANK() is a window function in SQL that assigns ranks to rows within a partition of a result set. Unlike RANK(), it does not skip ranks if there are duplicate values. This makes it ideal for scenarios like finding the second highest salary, where you want consecutive rankings.
To retrieve the second highest salary in each department, we can use the DENSE_RANK() function. Here’s how:
SELECT Name, Age, Salary, Department,
DENSE_RANK() OVER (PARTITION BY Department ORDER BY Salary DESC) AS Rank
FROM Employee;
To filter only the second highest salary, we use a Common Table Expression (CTE):
WITH RankedSalaries AS (
SELECT Name, Age, Salary, Department,
DENSE_RANK() OVER (PARTITION BY Department ORDER BY Salary DESC) AS Rank
FROM Employee
)
SELECT Name, Age, Salary, Department
FROM RankedSalaries
WHERE Rank = 2;
Name | Salary | DENSE_RANK() | RANK() |
---|---|---|---|
Rahul Kumar | 30000 | 1 | 1 |
Shubham Mishra | 20000 | 2 | 2 |
Using DENSE_RANK() is an efficient and reliable way to find the second highest salary in an SQL table. It ensures consecutive rankings and works seamlessly with the PARTITION BY clause to fetch department-specific results.
Follow us on Instagram, LinkedIn, Facebook, and Twitter for regular updates on SQL, database management, and interview questions!
This solution is provided by Shubham Mishra and contributed by the Developer Indian team. If you have any queries or suggestions, feel free to leave a comment! 🚀