Compensation benchmarking needs the third highest distinct salary inside each department.
From payroll_records, return department and third_highest_salary. Departments with fewer than three distinct salaries must be omitted entirely.
Sample data
Table: payroll_records
16 row(s) · showing first 8
| record_idINT | employee_nameTEXT | departmentTEXT | salaryINT |
|---|---|---|---|
| 1 | Ira Bansal | Analytics | 1900000 |
| 2 | Devansh Rao | Analytics | 1750000 |
| 3 | Nikhil Sarin | Analytics | 1600000 |
| 4 | Mahima Sethi | Analytics | 1600000 |
| 5 | Yusuf Ali | Analytics | 1400000 |
| 6 | Prerna Iyer | Engineering | 2400000 |
| 7 | Sagar Naik | Engineering | 2100000 |
| 8 | Rhea Kapoor | Engineering | 1850000 |
payroll_records
- record_idINT
- employee_nameTEXT
- departmentTEXT
- salaryINT
- Step 1: The answer has one row per department, so the outer query walks the departments and the heavy lifting happens in correlated subqueries.
- Step 2: The inner scalar subquery selects `DISTINCT salary` for the matching department, sorts descending, then skips two rows (`OFFSET 2`) and takes one (`LIMIT 1`) — that is the third highest distinct salary.
- Step 3: Correlation happens through `p2.department = p.department`, which makes the subquery re-evaluate per department.
- Step 4: A second correlated subquery counts distinct salaries so departments with fewer than three (Marketing, Support) are filtered out instead of returning `NULL`.
- Step 5: `SELECT DISTINCT` on the outer query collapses the repeated employee rows down to one row per department.
SELECT DISTINCT p.department,
(
SELECT DISTINCT p2.salary
FROM payroll_records AS p2
WHERE p2.department = p.department
ORDER BY p2.salary DESC
OFFSET 2
LIMIT 1
) AS third_highest_salary
FROM payroll_records AS p
WHERE (
SELECT COUNT(DISTINCT p3.salary)
FROM payroll_records AS p3
WHERE p3.department = p.department
) >= 3;Approach 2 — DENSE_RANK inside a CTE
Ranking distinct salaries per department is usually the more scalable formulation.
WITH ranked AS (
SELECT DISTINCT department,
salary,
DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rnk
FROM payroll_records
)
SELECT department, salary AS third_highest_salary
FROM ranked
WHERE rnk = 3;Learn the concept first
Stuck on Subqueries? These free SQL lessons teach it step by step.
More Subqueries questions
Practising alone only goes so far — our live cohorts pair SQL depth with dashboards, agentic analytics projects and mock interviews.
Explore the program