Description

Write a SQL query to find the 3rd highest distinct salary from the employees table. Return NULL if fewer than 3 distinct salaries exist. **Output columns (in order):** salary (or NULL if not found)

Table:employees
ColumnType
idINT
salaryINT

Examples

Input:CREATE TABLE employees (id INT, salary INT); INSERT INTO employees VALUES (1, 50000), (2, 60000), (3, 55000), (4, 60000);
Output:50000
Explanation:

The salaries are: 60000 (employees 2 and 4), 55000 (employee 3), and 50000 (employee 1). The distinct salaries in descending order are 60000, 55000, 50000. For N=3, the third highest distinct salary is 50000.

Input:CREATE TABLE employees (id INT, salary INT); INSERT INTO employees VALUES (1, 80000), (2, 75000), (3, 90000), (4, 85000), (5, 90000), (6, 80000);
Output:80000
Explanation:

The distinct salaries in descending order are: 90000, 85000, 80000, 75000. The third highest distinct salary is 80000, even though it appears twice in the original data.

Input:CREATE TABLE employees (id INT, salary INT); INSERT INTO employees VALUES (1, 45000), (2, 45000);
Output:NULL
Explanation:

There are only 2 employees with the same salary of 45000, which means there is only 1 distinct salary. Since the requirement is the 3rd highest distinct salary and there are fewer than 3 distinct salaries, the result is NULL.

Constraints

  • Return NULL if less than N salaries exist

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!