HomeInterview QuestionsWrite a stored procedure that takes a department I…

Write a stored procedure that takes a department ID as input and returns the department name, employee name, and the second highest salary for that department.

🟡 Medium Coding Junior level
1Times asked
Jun 2026Last seen
Jun 2026First seen

💡 Model Answer

Use a parameterized procedure and a window function to filter by the supplied department ID:

sql
CREATE PROCEDURE dbo.GetDeptSecondHighestById
    @DeptID INT
AS
BEGIN
    SELECT d.DepartmentName,
           e.EmployeeName,
           e.Salary
    FROM (
        SELECT e.EmployeeName,
               e.Salary,
               DENSE_RANK() OVER (ORDER BY e.Salary DESC) AS SalaryRank
        FROM Employees e
        WHERE e.DepartmentID = @DeptID
    ) AS ranked
    JOIN Departments d ON d.DepartmentID = @DeptID
    WHERE SalaryRank = 2;
END;

The procedure returns all employees who earn the second highest salary in the specified department. Complexity remains linear in the number of employees in that department. Call it with EXEC dbo.GetDeptSecondHighestById @DeptID = 5;.

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