Return the third highest DISTINCT salary using DENSERANK, aliased thirdhighest. Table definitions (from the source…
SQLLevel: IntermediateRanking and Top-N
Return the third highest DISTINCT salary using DENSE_RANK, aliased third_highest.
Table definitions (from the source exercise):
CREATE TABLE employees(emp_id INTEGER PRIMARY KEY, name TEXT, department_id INTEGER, manager_id INTEGER, salary INTEGER, hire_date TEXT, job_title TEXT, gender TEXT);
Hints
- Define one output row and the source-table keys.
- Check duplicates, NULLs and the order of filtering and aggregation.
Answer
Approach: DENSE_RANK over distinct salaries in a subquery; keep rank 3.
SELECT salary AS third_highest
FROM (
SELECT DISTINCT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS r
FROM employees
) x
WHERE r = 3;
The source uses SQLite with a MySQL compatibility layer. Date and string functions are dialect dependent; the query is preserved as published.
Source and licence: SQL Practice Lab — Ebrahim Sharifi · MIT