less than 1 minute read

Problem

[problem-176]

Query

SELECT
    (
        SELECT
            DISTINCT T.salary as SecondHighestSalary
        FROM
        (
            SELECT
                *,
                RANK() OVER (ORDER BY salary DESC) AS rnk
            FROM
                Employee e
        ) T
        WHERE
            T.rnk >= 2
        LIMIT 1
    ) SecondHighestSalary

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: