Problem
Task
Return the highest salary that is lower than the overall highest salary.
Schema
Table Schema
employees(id, name, salary)
Input
Sample Data
| id | name | salary |
|---|---|---|
| 1 | Mina | 90000 |
| 2 | Daniel | 78000 |
| 3 | Sofia | 90000 |
| 4 | Liam | 72000 |
Output
Expected Output
| second_highest_salary |
|---|
| 78000 |
Answer
Check Your Solution
Show Answer and Explanation
Correct Answer
SELECT MAX(salary) AS second_highest_salary
FROM employees
WHERE salary < (
SELECT MAX(salary)
FROM employees
);
Explanation
The subquery finds the overall highest salary. The outer query then finds the maximum salary below that value, which handles ties at the top.
Common Mistakes
- Using ORDER BY with an offset without considering duplicate top salaries.
- Using MIN instead of MAX in the outer query.
- Comparing salary <= maximum salary, which returns the top salary again.
Concepts
Related Concepts
Scalar Subqueries
MAX
Ranking Values
Subquery
Comparison
Next practice