Write a SQL query to find the second highest salary in a table.
Explanation:
To find the second highest salary in a table, we need a SQL query that considers distinct salary values and orders them appropriately. The challenge lies in efficiently filtering the second highest value from the dataset. This is a common problem in SQL interviews and tests your understanding of subqueries and ordering.
Key Talking Points:
- Understand the use of
DISTINCTto handle duplicate values. - Learn how to use subqueries to filter data.
- Grasp the concept of ordering data using
ORDER BY. - Get familiar with using
LIMITorOFFSETto select specific rows.
NOTES:
Reference Table:
| Method | Description | Pros | Cons |
|---|---|---|---|
| Subquery | Filters data using another query | Flexible and understandable | May have performance issues in large datasets |
LIMIT/OFFSET | Directly skips to the desired row | Simple and direct | Less intuitive for beginners |
| Common Table Expressions (CTEs) | Uses a named temporary result set | Readable and modular | Slightly more complex syntax |
Imagine a race where participants are ranked based on their finish time. To find the second fastest runner, you first list all the runners by their finish time, ignoring any ties. The runner with the second-lowest time is our target. Similarly, in SQL, we sort salaries and pick the second distinct value.
Pseudocode:
SELECT MAX(salary) AS SecondHighestSalary
FROM Employee
WHERE salary < (SELECT MAX(salary) FROM Employee);
Follow-Up Questions and Answers:
- Question: What if there are multiple people with the second highest salary?
- Answer: The query provided will still return the second highest salary, but if you need to list all employees with that salary, you can use:
SELECT * FROM Employee
WHERE salary = (SELECT MAX(salary) FROM Employee WHERE salary < (SELECT MAX(salary) FROM Employee));
-
Question: How would you find the nth highest salary?
- Answer: You can use a variation of the above query with modifications for nth values, possibly utilizing
DENSE_RANKorROW_NUMBERwindow functions.
- Answer: You can use a variation of the above query with modifications for nth values, possibly utilizing
-
Question: How can performance be improved for large datasets?
- Answer: Indexing the salary column can significantly improve query performance, especially for large datasets. Additionally, ensuring that subqueries are optimized to minimize execution time is crucial.
-
Question: How does the approach change if we're using a database that doesn't support
LIMITorOFFSET?- Answer: In such cases, you might rely more on subqueries or alternative SQL features like window functions if supported, such as
ROW_NUMBER()orRANK().
- Answer: In such cases, you might rely more on subqueries or alternative SQL features like window functions if supported, such as