LeetCode 176: Second Highest Salary
How to Solve LeetCode 176: Find the Second Highest Salary

I'm Varchasv, a Data Engineer working on enterprise data integration.
Currently on a 90-problem challenge to level up my technical skills and switch to a more development-focused role.
What I'm doing:
- Solving 2 Leetcode problems daily (SQL + DSA).
- Blogging about each problem.
- Building in public.
My Goal - Land a better data engineering role by mid-2026.
Follow my journey !!
Date: January 14, 2026
Category: SQL
Time Taken: 10 minutes
Difficulty: Medium
Problem Statement
Write a solution to find the second highest distinct salary from the Employee table. If there is no second-highest salary, return null.
Link: Second Highest Salary
My Approach
Initial thought:
I thought of using OFFSET and LIMIT in ORDER BY to get the second-highest salary, but in case of no second-highest salary, this solution will not return null.
Another brute force-ish solution would be to use CTE/subquery to find the second max salary less than the first max salary.
Final solution:
The best solution would be to use DENSE_RANK() and give every different salary a different rank, and we can just get the salary whose rank = 2. But it would still not return null; to accomplish that, we will add a SELECT statement wrapper at the end.
Why this works:
This works because this is a scalable solution; we just need to change the value of rank, and we can get the Nth highest salary.
Solution Code (Subquery)
SELECT MAX(salary) AS SecondHighestSalary
FROM Employee
WHERE salary < (SELECT MAX(salary) AS s1 FROM Employee)
Solution Code (Dense_rank)
SELECT (
SELECT DISTINCT salary
FROM (
SELECT salary , DENSE_RANK() OVER(ORDER BY salary DESC) AS rnk
FROM Employee
) AS ranked
WHERE rnk = 2
) AS secondHighestSalary
Key Takeaway: Whenever we need to get the Nth row from data, we should prefer window functions first.
Pattern: Window Functions
Mistakes I Made: I considered solving this without window functions, but I should have realized it would require a window function solution. I also had trouble remembering the syntax of window functions.
Series: 90 Days of Data Engineering Progress: 3/90 problems completed
Tags: #DEQuest #LeetCode #SQL #DataEngineering #BuildInPublic