Second Highest Salary II solution and explanation
The problem
Table: employees
+------------------+---------+ | Column Name | Type | +------------------+---------+ | emp_id | int | | salary | int | | dept | varchar | +------------------+---------+ emp_id is the unique key for this table. Each row of this table contains information about an employee including their ID, salary, and department.
Write a solution to find the employees who earn the second-highest salary in each department. If multiple employees have the second-highest salary, include all employees with that salary.
Return the result table ordered by emp_id in ascending order.
The result format is in the following example.
Example:
Input:
employees table:
+--------+--------+-----------+ | emp_id | salary | dept | +--------+--------+-----------+ | 1 | 70000 | Sales | | 2 | 80000 | Sales | | 3 | 80000 | Sales | | 4 | 90000 | Sales | | 5 | 55000 | IT | | 6 | 65000 | IT | | 7 | 65000 | IT | | 8 | 50000 | Marketing | | 9 | 55000 | Marketing | | 10 | 55000 | HR | +--------+--------+-----------+
Output:
+--------+-----------+ | emp_id | dept | +--------+-----------+ | 2 | Sales | | 3 | Sales | | 5 | IT | | 8 | Marketing | +--------+-----------+
Explanation:
- Sales Department:
- Highest salary is 90000 (emp_id: 4)
- Second-highest salary is 80000 (emp_id: 2, 3)
- Both employees with salary 80000 are included
- IT Department:
- Highest salary is 65000 (emp_id: 6, 7)
- Second-highest salary is 55000 (emp_id: 5)
- Only emp_id 5 is included as they have the second-highest salary
- Marketing Department:
- Highest salary is 55000 (emp_id: 9)
- Second-highest salary is 50000 (emp_id: 8)
- Employee 8 is included
- HR Department:
- Only has one employee
- Not included in the result as it has fewer than 2 employees
Approach overview
Problem Overview: You need to return the second highest distinct salary from a database table. If a second highest value does not exist, the query should return NULL. The challenge is handling duplicates correctly while keeping the query concise and efficient.
Approach 1: Subquery with ORDER BY and OFFSET (O(n log n) time, O(1) extra space)
One direct approach is sorting distinct salaries in descending order and selecting the second entry. In MySQL, this is done using SELECT DISTINCT salary FROM Employee ORDER BY salary DESC LIMIT 1 OFFSET 1. The database engine sorts all unique salaries, then skips the first (highest) value. Sorting dominates the cost, giving O(n log n) time. This approach works well for quick queries but can feel brittle if the schema evolves or additional ranking logic is needed.
Approach 2: Window Function with DENSE_RANK (O(n log n) time, O(n) space)
Window functions provide a cleaner and more scalable solution. Use DENSE_RANK() over salaries ordered descending to assign ranks where equal salaries share the same rank. The highest salary receives rank 1, the second distinct salary receives rank 2. After computing ranks, filter rows where rank = 2. This method naturally handles duplicates and is widely supported in modern SQL engines. The ranking operation internally requires sorting, leading to O(n log n) time and O(n) intermediate space.
Example pattern:
SELECT salary FROM (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) r FROM Employee) t WHERE r = 2;
This approach is common in analytics queries and translates well to data processing tools like pandas. It also builds intuition for solving ranking problems with SQL window functions such as DENSE_RANK, RANK, and ROW_NUMBER.
Recommended for interviews: The window function approach using DENSE_RANK() is typically expected. It demonstrates strong SQL fundamentals and shows you understand how to handle duplicates with ranking semantics. The simple subquery approach proves you understand ordering and filtering, but the window function solution signals deeper knowledge of modern SQL patterns used in production data systems.
Solution
We can use the DENSE_RANK() window function to rank employees in each department by salary in descending order, and then filter out the employees with a rank of 2.
# Write your MySQL query statement below
WITH
T AS (
SELECT
emp_id,
dept,
DENSE_RANK() OVER (
PARTITION BY dept
ORDER BY salary DESC
) rk
FROM Employees
)
SELECT emp_id, dept
FROM T
WHERE rk = 2
ORDER BY 1;import pandas as pd
def find_second_highest_salary(employees: pd.DataFrame) -> pd.DataFrame:
employees["rk"] = employees.groupby("dept")["salary"].rank(
method="dense", ascending=False
)
second_highest = employees[employees["rk"] == 2][["emp_id", "dept"]]
return second_highest.sort_values(by="emp_id")Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Subquery with DISTINCT + ORDER BY + OFFSET | O(n log n) | O(1) | Quick solution when the database supports LIMIT/OFFSET and the dataset is moderate. |
| Window Function (DENSE_RANK) | O(n log n) | O(n) | Preferred modern SQL approach. Handles duplicates cleanly and scales well for ranking problems. |
Frequently asked questions
Is Second Highest Salary II easy or hard?
Second Highest Salary II is generally considered a medium-level SQL problem. The challenge comes from handling duplicate salaries correctly and returning NULL when a second highest value does not exist. Understanding window functions like DENSE_RANK() makes the solution straightforward.
Second Highest Salary II Python/Java solution
For SQL problems like this, the implementation is written as a database query rather than Python or Java code. In data processing workflows, a similar approach can be implemented in pandas using rank or sorting operations. The same idea applies: rank salaries descending and select the second distinct value.
How to solve Second Highest Salary II in O(n)?
Pure O(n) solutions are uncommon in SQL because ranking typically requires sorting. Some theoretical approaches using aggregates like MAX(salary) with a conditional filter (salary < max_salary) can reduce work but still depend on scans and optimizer behavior. In practice, databases implement these queries with sorting, giving O(n log n) performance.
What is the best approach for Second Highest Salary II?
The most reliable solution uses the SQL window function DENSE_RANK() ordered by salary in descending order. Assign ranks to each distinct salary and filter for rank = 2. This approach handles duplicate salaries naturally and keeps the query easy to extend. Time complexity is O(n log n) due to sorting.
Is Second Highest Salary II asked at Google/Amazon/Meta?
Variants of the 'second highest value' query are common in SQL interviews at companies like Amazon, Google, and Meta. Interviewers use it to test understanding of ranking functions, DISTINCT handling, and subqueries. The window function solution using DENSE_RANK() is often the expected answer.
What data structure is used in Second Highest Salary II?
The problem relies on relational database operations rather than traditional data structures. Internally, the database engine performs sorting and ranking operations. Window functions such as DENSE_RANK() conceptually assign ordered ranks to rows based on salary values.
What is the time complexity of Second Highest Salary II?
Most SQL solutions require sorting salaries in descending order, which results in O(n log n) time complexity. Window function approaches like DENSE_RANK() and subqueries using ORDER BY both rely on sorting. Space complexity is typically O(n) for window functions and O(1) extra space for simpler subqueries.


