Problems / Second Highest Salary / Editorial
(SELECT MAX(salary) FROM employees)
SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees)
employee_id
The PySpark version makes the "distinct levels" idea explicit: select("salary").distinct(), sort descending, limit(2), then MIN of those two rows is the second level. A one-row crossJoin broadcasts it back onto every employee for the final filter.
select("salary").distinct()
limit(2)
MIN
crossJoin
ORDER BY salary DESC LIMIT 1 OFFSET 1 is the tempting shortcut, and it fails twice here: without DISTINCT the offset lands on a duplicate of the top salary, and with LIMIT 1 it returns a single employee even when several tie at the second level. The max-below-max subquery handles both tie scenarios by construction — which is exactly why interviewers seed the data with ties.
ORDER BY salary DESC LIMIT 1 OFFSET 1
DISTINCT
LIMIT 1
Solve Second Highest Salary yourself →