Write a solution to find the 5th highest distinct salary from the Employee table. If there are fewer than 5 distinct salaries, return NULL.
The result should be a single column named NthHighestSalary.
Input Table(s)
Table: Employee
| Column | Type | Meaning |
|---|
id | INT | Employee identifier (primary key) |
salary | INT | The employee's salary, NOT NULL |
Key: id is the primary key, so every row is a different employee. The same salary value can appear on several rows.
Output Contract
-
Exactly one row with one column,
NthHighestSalary
, holding an integer or
NULL
.
-
The value is the 5th largest distinct
salary
. It is
NULL
when the table has fewer than 5 distinct salaries.
-
The result always has a single row, so it needs no ordering. Salaries are integers, so no rounding applies.
-
Keep the capital letters in the column name. In PostgreSQL that means quoting the alias as
"NthHighestSalary"
.
Example
Example 1
Input Employee:
| id | salary |
|---|
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
| 4 | 400 |
| 5 | 500 |
| 6 | 600 |
Output:
There are 6 distinct salaries. Sorted descending: 600, 500, 400, 300, 200, 100. The 5th highest is 200.
Example 2
Input Employee:
Output:
There are only 3 distinct salaries, fewer than 5, so the result is one row holding NULL.
Example 3: repeated salaries
Input Employee:
| id | salary |
|---|
| 1 | 700 |
| 2 | 700 |
| 3 | 600 |
| 4 | 500 |
| 5 | 400 |
| 6 | 300 |
Output:
The distinct salaries are 700, 600, 500, 400, 300, so the 5th highest is 300. Counting rows instead of distinct values would land on 400.
Constraints and Clarifications
-
The table has 1 to 10,000 rows.
-
salary
is an integer from 0 to 100,000 and is never NULL. A salary of 0 counts like any other value.
-
A salary shared by several employees counts once.
-
When there are exactly 5 distinct salaries, the answer is the smallest one.
-
When there are fewer than 5 distinct salaries, the output is still one row, with
NthHighestSalary
set to
NULL
.