Return name, departmentid, salary of employees whose salary is at least 90 percent of their departments maximum. Table…
SQLLevel: IntermediateAbove-average and subqueries
Return name, department_id, salary of employees whose salary is at least 90 percent of their departments maximum.
Table definitions (from the source exercise):
CREATE TABLE departments(department_id INTEGER PRIMARY KEY, department_name TEXT, created_date TEXT);
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: Correlated MAX subquery times 0.9.
SELECT e.name, e.department_id, e.salary
FROM employees e
WHERE e.salary >= 0.9 * (SELECT MAX(salary) FROM employees d
WHERE d.department_id = e.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