Write a stored procedure that returns the department name and the second highest salary.
1Times asked
Jun 2026Last seen
Jun 2026First seen
💡 Model Answer
To get the department name and the second highest salary, you can use a window function to rank salaries within each department. In T‑SQL:
sql
CREATE PROCEDURE dbo.GetDeptSecondHighest
AS
BEGIN
SELECT DepartmentName,
MAX(Salary) AS SecondHighestSalary
FROM (
SELECT d.DepartmentName,
e.Salary,
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
) AS ranked
WHERE SalaryRank = 2
GROUP BY DepartmentName;
END;The DENSE_RANK assigns 1 to the highest salary, 2 to the second highest, etc. The outer query filters for rank 2 and groups by department. Complexity is O(n) for scanning the tables plus O(n log n) for the window function, which is acceptable for typical datasets. The procedure can be called with EXEC dbo.GetDeptSecondHighest;.
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