Second Highest Salary - Problem
๐ข Find the Second Highest Salary
You're working as a data analyst at a tech company and need to find the second highest distinct salary from the employee database. This is a common task in HR analytics!
Given an Employee table with the following structure:
| Column Name | Type |
|---|---|
| id | int |
| salary | int |
Key Points:
idis the primary key (unique values)- Each row contains salary information for one employee
- Multiple employees can have the same salary
- If there's no second highest salary, return
null
Your task: Write a SQL query to find the second highest distinct salary. Remember, we want the second unique salary value, not the second occurrence!
Input & Output
example_1.sql โ Basic Case
$
Input:
Employee table:
+----+--------+
| id | salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
โบ
Output:
SecondHighestSalary: 200
๐ก Note:
The distinct salaries are [300, 200, 100]. The second highest distinct salary is 200.
example_2.sql โ Duplicate Salaries
$
Input:
Employee table:
+----+--------+
| id | salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 200 |
| 4 | 100 |
+----+--------+
โบ
Output:
SecondHighestSalary: 100
๐ก Note:
The distinct salaries are [200, 100]. Even though 200 appears twice and 100 appears twice, we only consider unique values. The second highest distinct salary is 100.
example_3.sql โ No Second Highest
$
Input:
Employee table:
+----+--------+
| id | salary |
+----+--------+
| 1 | 100 |
| 2 | 100 |
| 3 | 100 |
+----+--------+
โบ
Output:
SecondHighestSalary: null
๐ก Note:
All employees have the same salary (100), so there is only one distinct salary. Since there's no second highest distinct salary, we return null.
Visualization
Tap to expand
Understanding the Visualization
1
Collect Employee Data
Gather all employee salaries from the database, including potential duplicates
2
Identify Unique Salary Levels
Find distinct salary amounts to understand the pay structure
3
Rank Salary Tiers
Sort salaries from highest to lowest to create a ranking system
4
Extract Second Tier
Select the second-highest distinct salary for analysis
Key Takeaway
๐ฏ Key Insight: The secret to solving this problem correctly is understanding that we want the second distinct salary value, not the second occurrence. DENSE_RANK() window function is perfect for this because it assigns consecutive ranks without gaps, even when there are ties!
Time & Space Complexity
Time Complexity
O(n log n)
Sorting for ranking, but done efficiently by the database engine
โก Linearithmic
Space Complexity
O(n)
Space for ranking intermediate results
โก Linearithmic Space
Constraints
- The Employee table contains at least 0 rows
- Salary values are integers and can be negative
- id is the primary key with unique values
-
Important: Return exactly
null(not 0 or empty) when no second highest exists
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code