Second Highest Salary Leetcode Solution

0



+-------------+------+
| Column Name | Type |
+-------------+------+
| id | int |
| salary | int |
+-------------+------+
id is the primary key column for this table.
Each row of this table contains information about the salary of an employee.

Write an SQL query to report the second highest salary from the Employee table. If there is no second highest salary, the query should report null.

The query result format is in the following example.

Example 1:


Input:
Employee table:
+----+--------+
| id | salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+

Output:
+---------------------+
| SecondHighestSalary |
+---------------------+
| 200 |
+---------------------+

Example 2:


Input:
Employee table:
+----+--------+
| id | salary |
+----+--------+
| 1 | 100 |
+----+--------+

Output:
+---------------------+
| SecondHighestSalary |
+---------------------+
| null |
+---------------------+

Second Highest Salary Solution


SELECT max(salary) as SecondHighestSalary
FROM Employee WHERE salary NOT IN(SELECT max(salary) FROM Employee)

The SQL query above retrieves the second highest salary from the Employee table.

Here's how it works:

  • The "SELECT max(salary) FROM Employee" statement returns the highest salary value in the Employee table.
  • The "NOT IN" operator is used to exclude any rows from the Employee table that have the highest salary value.
  • The "SELECT max(salary) as SecondHighestSalary" statement then selects the maximum salary value from the remaining rows in the Employee table, which is the second highest salary.

Disclaimer: The above Problem is generated by Leetcode but the Solution is provided by ShouterFolk.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)
Our website uses cookies to enhance your experience. Learn More
Accept !