Retrieve the second highest salary along with the department name.
1Times asked
Jun 2026Last seen
Jun 2026First seen
💡 Model Answer
Use a window function to rank salaries per department and filter for rank 2:
sql
SELECT DepartmentName,
SecondHighestSalary
FROM (
SELECT d.DepartmentName,
MAX(e.Salary) AS SecondHighestSalary,
DENSE_RANK() OVER (PARTITION BY d.DepartmentID ORDER BY e.Salary DESC) AS SalaryRank
FROM Employees e
JOIN Departments d ON e.DepartmentID = d.DepartmentID
GROUP BY d.DepartmentID, d.DepartmentName
) AS ranked
WHERE SalaryRank = 2;This returns each department’s second highest salary. The query is linear in the number of employee records plus the cost of the window function, making it efficient for typical workloads.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers — invisible to screen sharing.
Get Assisting AI — Starts at ₹500