Hi guys, let's start a SQL interview series covering frequently asked and important SQL interview questions.
Each part will cover 1 practical interview question with:
✅ Problem statement
✅ SQL solution
✅ Approach
✅ Interview tip
📌 Question 1: Find the Second Highest Salary
Suppose you have an Employee table:
Employee
• employee_id
• employee_name
• salary
Example data:
employee_id| employee_name| salary
1| Amit| 50000
2| Rahul| 80000
3| Priya| 70000
4| Neha| 90000
5| Raj| 80000
❓ Find the second-highest salary from the Employee table.
💡 Approach
First, we need to identify the highest salary.
Then, we need the highest salary that is less than the maximum salary.
One simple approach is to use a subquery:
SELECT MAX(salary) AS second_highest_salary
FROM Employee
WHERE salary < (
SELECT MAX(salary)
FROM Employee
);
Output:
second_highest_salary
80000
🔎 Why does this work?
The inner query:
SELECT MAX(salary)
FROM Employee;
returns:
90000
Then the outer query considers only salaries below 90000:
50000
70000
80000
80000
Finally, MAX() returns:
80000
⚠️ Important Interview Point
If the question asks for the second-highest DISTINCT salary, this approach works because duplicate salaries are naturally treated as one value.
For example:
90000
80000
80000
70000
The second-highest distinct salary is still 80000.
💯 Double Tap ❤️ For Part-2