Table: Employee
+-------------+------+
| Column Name | Type |
+-------------+------+
| id | int |
| salary | int |
+-------------+------+
id is the primary key (column with unique values) for this table.
Each row of this table contains information about the salary of an employee.
Write a SQL query to find the second highest distinct salary from the Employee
table. If there is no second highest salary, return null
.
The result format is in the following example.
Example 1:
Input:
Employee table:
+----+--------+
| id | salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
Output:
+---------------------+
| SecondHighestSalary |
+---------------------+
| 200 |
+---------------------+
Example 2:
Input:
Employee table:
+----+--------+
| id | salary |
+----+--------+
| 1 | 100 |
+----+--------+
Output:
+---------------------+
| SecondHighestSalary |
+---------------------+
| null |
+---------------------+
-- Approach: Using subquery and LIMIT clause
SELECT
(SELECT DISTINCT
salary
FROM
Employee
ORDER BY
salary DESC
LIMIT 1 OFFSET 1) AS SecondHighestSalary;
LIMIT 1
restricts the result to a single row.OFFSET 1
skips the first row (which is the highest salary), effectively selecting the second highest.NULL
. This handles the case where there is only one distinct salary or no salaries at all.DENSE_RANK()
Window Function):SELECT
(SELECT DISTINCT salary
FROM (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) as rank
FROM Employee
) AS ranked_salaries
WHERE rank = 2) AS SecondHighestSalary;
DENSE_RANK()
ensures that consecutive ranks are assigned even if there are duplicate salaries.NULL
.Employee
table is empty, both queries will return NULL
, which is the desired behavior.NULL
.DISTINCT
keyword ensures that duplicate salary values are treated as one. Both queries correctly handle cases with duplicate salaries and return the second highest distinct salary.salary
column contains negative values, the queries will still work correctly, as the ORDER BY
clause sorts the salaries based on their numerical value, regardless of sign.