"Second highest salary" usually means the second highest distinct salary, so duplicate top salaries should not count twice. Here are several correct approaches; knowing more than one shows depth. 1. Subquery with MAX (works in every SQL database) SELECT MAX(Salary) AS SecondHighestSalary FROM Employees WHERE Salary < (SELECT MAX(Salary) FROM Employees); - Returns NULL when there is no second distinct salary, which is a sensible answer. 2. DENSE_RANK window function (handles ties and generalises to Nth highest) WITH Ranked AS ( SELECT Name, Salary, DENSE_RANK() OVER (ORDER BY Salary DESC) AS rnk FROM Employees ) SELECT Name, Salary FROM Ranked WHERE rnk = 2; - Returns every employee who earns the second highest salary. Change 2 to N for the Nth highest. - Use DENSE_RANK, not ROW_NUMBER (which would pick an arbitrary row among ties) or RANK (which skips numbers after ties). 3. OFFSET/FETCH with DISTINCT (SQL Server 2012+, PostgreSQL and MySQL with LIMIT/OFFSET) SELECT DISTINCT Salary FROM Employees ORDER BY Salary DESC OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY; -- MySQL / PostgreSQL: SELECT DISTINCT Salary FROM Employees ORDER BY Salary DESC LIMIT 1 OFFSET 1; - Returns no row (rather than NULL) when there is no second salary. Wrap it in SELECT (...) AS SecondHighestSalary if NULL is required. 4. TOP with a subquery (classic SQL Server) SELECT TOP 1 Salary FROM (SELECT DISTINCT TOP 2 Salary FROM Employees ORDER BY Salary DESC) AS t ORDER BY Salary ASC; Per-department second highest salary WITH Ranked AS ( SELECT DepartmentId, Name, Salary, DENSE_RANK() OVER (PARTITION BY DepartmentId ORDER BY Salary DESC) AS rnk FROM Employees ) SELECT DepartmentId, Name, Salary FROM Ranked WHERE rnk = 2; Edge cases to mention - Duplicate highest salaries: 50000, 50000, 40000 should give 40000. - Only one employee or all salaries equal: return NULL or no rows — state which you choose. - NULL salaries: MAX and DENSE_RANK ignore or sort NULLs differently by database; filter them with WHERE Salary IS NOT NULL if needed. - Performance: an index on Salary (or (DepartmentId, Salary DESC) for the partitioned version) avoids full sorts on large tables.
Ravindra Wadile · · 0 likes