Skip to content
Quantoros

For each departmentid, return the second highest DISTINCT salary WITHOUT window functions, aliased secondsal. Table…

SQLLevel: IntermediateRanking and Top-N

For each department_id, return the second highest DISTINCT salary WITHOUT window functions, aliased second_sal.

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
  • Which rows belong to the partition and frame for each current row?
  • Check ordering, ties, frame boundaries and the difference from GROUP BY.

Answer

Approach: Per department: MAX(salary) below that departments MAX - a correlated subquery inside a grouped query.

SELECT department_id, MAX(salary) AS second_sal
FROM employees e
WHERE salary < (SELECT MAX(salary) FROM employees m
                WHERE m.department_id = e.department_id)
GROUP BY department_id;

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