Second Highest Salary
Return the second-highest distinct salary, or NULL when it does not exist.
Start practiceProblem statement
Prompt
Given the employee table below, write a query that returns the second-highest distinct salary from the salary column.
- "Distinct" means identical salaries count once. If three employees earn 100, 100, and 90, the salaries are 100 and 90, so the answer is 90.
- If there is no second-highest salary (fewer than two distinct salaries, or an empty table), the query must return one row with a `NULL` value — not zero rows.
NULLsalaries must be ignored: they are not a value and should never be returned as the answer.
The result should have a single column (name it second_highest_salary) and a single row.
Example
| id | salary |
|---|---|
| 1 | 100 |
| 2 | 100 |
| 3 | 90 |
| 4 | 80 |
Expected result:
| second_highest_salary |
|---|
| 90 |
Constraints
employee.idis the primary key and is neverNULL.employee.salarymay beNULL.
Tips
- Think about what happens with duplicates before you write
LIMIT 1 OFFSET 1— an unorderedDISTINCT+OFFSETapproach is fragile. - Aggregates like
MAXover a set of values are a clean way to guarantee "one row, orNULLwhen empty".
Schema
CREATE TABLE employee (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
salary INTEGER -- NULL allowed
);
Sample data
INSERT INTO employee (id, name, salary) VALUES
(1, 'Alice', 100),
(2, 'Bob', 100),
(3, 'Carol', 90),
(4, 'Dave', 80),
(5, 'Eve', 75);
Additional hidden fixtures are applied during validation to test edge cases.
Solution
One correct approach — try solving it yourself in the practice editor first, then compare. There is usually more than one valid solution.
-- Reference: second-highest distinct salary, ignoring NULLs, as a single row.
WITH distinct_salaries AS (
SELECT DISTINCT salary
FROM employee
WHERE salary IS NOT NULL
)
SELECT MAX(salary) AS second_highest_salary
FROM distinct_salaries
WHERE salary < (SELECT MAX(salary) FROM distinct_salaries);
Key concepts
- SELECT
- DISTINCT
- Subquery in FROM
- Aggregate MAX
- NULL handling
Related questions
- easyCustomers Without OrdersList customers who have never placed an order using an anti-join.
- mediumImmediate Food DeliveryReport the percentage of customers' first orders that were delivered immediately.
- mediumNth Highest SalaryReturn the third-highest distinct salary, or NULL when it does not exist.
- easyActive Users Per DayReport the number of distinct active users for each date of activity.
- easyAverage Process Time Per MachineCompute each machine's average time to complete a process.