Second Highest Salary
Write an SQL query to find the second highest distinct salary from the **Employee** table. If there is no second highest salary, return `null`. ### Table: Employee | Column Name | Type | | :--- | :--- | | id | int | | salary | int | `id` is the primary key column for this table. Each row contains information about the salary of an employee. ### Example 1: **Input:** ```text Employee table: +----+--------+ | id | salary | +----+--------+ | 1 | 100 | | 2 | 200 | | 3 | 300 | +----+--------+ ``` **Output:** ```text +---------------------+ | SecondHighestSalary | +---------------------+ | 200 | +---------------------+ ``` ### Example 2: **Input:** ```text Employee table: +----+--------+ | id | salary | +----+--------+ | 1 | 100 | +----+--------+ ``` **Output:** ```text +---------------------+ | SecondHighestSalary | +---------------------+ | null | +---------------------+ ```
Solve It in the BrowserPractice Explaining It Out Loud
Optimal Approach
- Time complexity: O(N)
- Space complexity: O(1)
Scanning the table twice for MAX aggregates takes linear time O(N) where N is the number of rows.
Follow-Up Questions Interviewers Ask About Second Highest Salary
- How would you handle finding the Nth highest salary in SQL?
You can use the window function DENSE_RANK() OVER (ORDER BY salary DESC) in a Common Table Expression (CTE) or subquery, then filter WHERE rank = N. - Why does MAX() return NULL if no row satisfies the WHERE condition?
SQL aggregate functions without a GROUP BY clause always return exactly one row. When no rows match the filter, MAX() evaluates to NULL, satisfying the problem requirement without needing an explicit IFNULL() or COALESCE().
Practice the full problem with execution, tests, and AI code review in the interactive lab — then rehearse explaining your solution in a live voice mock interview.