Given a table employees with employee information including their ID, salary, and department, write a SQL query to find the employees who earn the second-highest salary in each department.
Key Requirements:
- Find the second-highest salary within each department
- If multiple employees have the same second-highest salary, include all of them
- If a department has fewer than 2 distinct salary levels, exclude it from results
- Return results ordered by
emp_idin ascending order
Table Schema
| Column Name | Type | Description |
|---|---|---|
emp_id
PK
|
int | Unique employee identifier (primary key) |
salary
|
int | Employee's salary amount |
dept
|
varchar | Department name where employee works |
Input & Output
| 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 |
| emp_id | dept |
|---|---|
| 2 | Sales |
| 3 | Sales |
| 5 | IT |
| 8 | Marketing |
Sales: Highest is 90000 (emp_id 4), second-highest is 80000 (both emp_id 2 and 3 included due to tie)
IT: Highest is 65000 (emp_id 6,7), second-highest is 55000 (emp_id 5)
Marketing: Highest is 55000 (emp_id 9), second-highest is 50000 (emp_id 8)
HR: Only one salary level (55000), so no second-highest exists - excluded from results
| emp_id | salary | dept |
|---|---|---|
| 1 | 100000 | Engineering |
| 2 | 100000 | Engineering |
| 3 | 100000 | Engineering |
| 4 | 75000 | Finance |
| 5 | 80000 | Finance |
| emp_id | dept |
|---|---|
| 4 | Finance |
Engineering: All employees have the same salary (100000), so there's only one distinct salary level. No second-highest exists - excluded from results.
Finance: Highest is 80000 (emp_id 5), second-highest is 75000 (emp_id 4).
| emp_id | salary | dept |
|---|---|---|
| 1 | 90000 | Sales |
| 2 | 60000 | IT |
| emp_id | dept |
|---|
Each department has only one employee, so neither department has a second-highest salary. The result is empty.
Constraints
-
1 ≤ emp_id ≤ 10^4 -
1 ≤ salary ≤ 10^6 -
deptis a non-empty string -
Each
emp_idis unique