Forum

Write an SQL Query ...
 
Share:
Notifications
Clear all

Write an SQL Query to Find Employees with the Second Highest Salary in Each Department


Posts: 71
Guest
Topic starter
(@Vinay Kumar)
Trusted Member
Joined: 4 years ago

How can you write an SQL query to find employees with the second highest salary in each department? Assume you have an employees table with columns employee_id, department, employee_name, and salary.

Answer:

To find employees with the second highest salary in each department, we can use the DENSE_RANK() window function to rank salaries within each department and filter for the second rank.

Solution: Using DENSE_RANK()

Assume the employees table structure is as follows:

employee_id department employee_name salary
1 HR Alice 70000
2 IT Bob 90000
3 HR Carol 80000
4 IT Dave 85000
5 IT Eve 95000
6 Sales Frank 75000
7 Sales Grace 70000

To find the second highest salary in each department:

SQL Query:

sql
 
SELECT employee_id, department, employee_name, salary
FROM (
SELECT employee_id, department, employee_name, salary,
DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS salary_rank
FROM employees
) AS ranked_salaries
WHERE salary_rank = 2;

Explanation:

  1. DENSE_RANK() with PARTITION BY department: This assigns a rank to each salary within each department, ordering from highest to lowest.
  2. Filtering for Rank 2: The WHERE salary_rank = 2 clause retrieves only employees ranked second in salary within their department.

Expected Output:

Based on the example data, the result would look like:

employee_id department employee_name salary
1 HR Alice 70000
4 IT Dave 85000
6 Sales Frank 75000

Alternative Solution: Using a Subquery (if DENSE_RANK() is unavailable)

In cases where DENSE_RANK() is unsupported, a subquery can be used to retrieve the distinct top two salaries in each department and then select the second highest.

SQL Query for Alternative Solution:

sql
 
SELECT employee_id, department, employee_name, salary
FROM employees e
WHERE salary = (
SELECT DISTINCT salary
FROM employees
WHERE department = e.department
ORDER BY salary DESC
LIMIT 1 OFFSET 1
);

Explanation of Alternative Solution:

  1. Subquery for Top 2 Salaries: The inner query finds the second-highest salary in each department by ordering salaries in descending order and skipping the highest.
  2. Main Query Filters by Salary: The main query then selects employees who match the second-highest salary for each department.

Leave a reply

Author Name

Author Email

Title *

 
Preview 0 Revisions Saved
Share: