less than 1 minute read

Problem

problem-176

Query

First implementation

SELECT
    IF(COUNT(*) = 0, NULL, e1.salary) as SecondHighestSalary
FROM
    Employee as e1,
    (
        SELECT *
        FROM Employee
        GROUP BY salary
        ORDER BY salary DESC
        LIMIT 1 OFFSET 1
    ) as e2
WHERE
    e1.id = e2.id

Second implementation

SELECT
    IF(COUNT(*) = 0, NULL, e1.salary) as SecondHighestSalary
FROM
    Employee as e1,
    (
        SELECT DISTINCT salary
        FROM Employee
        ORDER BY salary DESC
        LIMIT 1 OFFSET 1
    ) as e2
WHERE
    e1.salary = e2.salary

Editorial Solution

Approach 1: Using sub-query and LIMIT clause

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

Approach 2: Using IFNULL and LIMIT clause

SELECT
    IFNULL(
      (SELECT DISTINCT Salary
       FROM Employee
       ORDER BY Salary DESC
        LIMIT 1 OFFSET 1),
    NULL) AS SecondHighestSalary

Tags:

Updated: