Write a SQL query to retrieve the department, employee name, employee ID, and salary of the employee with the second highest salary in each department using dense_rank.
💡 Model Answer
The query you provided is almost correct but missing a closing parenthesis and an alias for the subquery. Here is the corrected version:
SELECT department, employee_name, employee_id, salary
FROM (
SELECT e.department,
e.employee_name,
e.employee_id,
s.salary,
DENSE_RANK() OVER (PARTITION BY e.department ORDER BY s.salary DESC) AS rnkFROM employee e
JOIN salary s USING (employee_id)
) AS sub
WHERE rnk = 2;
Explanation: The inner SELECT joins employee and salary, then assigns a rank per department. The outer SELECT filters for rank 2, giving the second highest salary per department. Complexity is dominated by the sort in the window function, O(n log n).
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 on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500