test sql practice

Table: Employee

+-------------+------+
| Column Name | Type |
+-------------+------+
| id          | int  |
| salary      | int  |
+-------------+------+
id is the primary key.

Write a query to find the second highest distinct salary from the Employee table. If there is no second highest salary, return NULL.

Name the column SecondHighestSalary.

Example 1

Employee: (1, 100), (2, 200), (3, 300) Output: SecondHighestSalary = 200

Example 2

Employee: (1, 100) Output: SecondHighestSalary = NULL
Duplicates matter: two people earning 300 do not make 300 the second highest.
A scalar subquery returns NULL when it finds no rows. Wrap your query in SELECT (…) AS SecondHighestSalary.

Option 1: LIMIT / OFFSET

SELECT (
  SELECT DISTINCT salary
  FROM Employee
  ORDER BY salary DESC
  LIMIT 1 OFFSET 1
) AS SecondHighestSalary;

Option 2: MAX below the MAX

SELECT MAX(salary) AS SecondHighestSalary
FROM Employee
WHERE salary < (SELECT MAX(salary) FROM Employee);

Option 3: window function

SELECT MAX(salary) AS SecondHighestSalary
FROM (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk FROM Employee)
WHERE rnk = 2;

Follow-up interviewers love: generalise to the N-th highest salary.

Next Post Previous Post
No Comment
Add Comment
comment url