Retrieve employees who receive the second highest salary within their department.
1Times asked
Jun 2026Last seen
Jun 2026First seen
💡 Model Answer
A single query can list all such employees:
sql
SELECT d.DepartmentName,
e.EmployeeName,
e.Salary
FROM (
SELECT e.*,
DENSE_RANK() OVER (PARTITION BY e.DepartmentID ORDER BY e.Salary DESC) AS SalaryRank
FROM Employees e
) AS ranked
JOIN Departments d ON d.DepartmentID = ranked.DepartmentID
WHERE ranked.SalaryRank = 2;DENSE_RANK ensures that ties are handled correctly; if two employees share the highest salary, the next distinct salary gets rank 2. The query runs in O(n) time plus the cost of the window function, which is efficient for most tables.
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