Skip to content
Quantoros

Return the second highest distinct salary in employees, aliased secondhighest. Table definitions (from the source…

SQLLevel: IntermediateRanking and Top-N

Return the second highest distinct salary in employees, aliased second_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: MAX below MAX, or ORDER BY DESC LIMIT 1 OFFSET 1 on DISTINCT salaries.

SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);

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

Related questions