Second Highest Salary

SQL coding challenge · Difficulty: easy · +50 XP

Table: salaries

+----------+---------+

| Column   | Type    |

+----------+---------+

| emp_id   | INT     |
| name     | VARCHAR |
| salary   | INT     |

+----------+---------+

Problem

-------

Find the second highest DISTINCT salary.

If there is no second highest salary,

return NULL.

Return column name: second_highest_salary

Example 1

---------

Input:

+--------+-------+--------+

| emp_id | name  | salary |

+--------+-------+--------+

|   1    | Alice | 90000  |
|   2    | Bob   | 75000  |
|   3    | Carol | 90000  |
|   4    | Dave  | 60000  |

+--------+-------+--------+

Output:

+----------------------+

| second_highest_salary|

+----------------------+

|        75000         |

+----------------------+

Explanation: Distinct salaries are

90000, 75000, 60000.

Second highest = 75000.

Example 2 (Edge case — only 1 salary)

--------------------------------------

Input: All employees earn 90000

Output: NULL

Hint

----

SELECT MAX(salary) AS second_highest_salary

FROM salaries

WHERE salary < (SELECT MAX(salary)

FROM salaries)

Solve this challenge on PySpark.in