cswork / libraryOpen practice workspace

Coding questions · Otter.Ai

Find the Highest-Paid Employee in Each Department

Work through a tie-aware PostgreSQL problem that finds every highest-paid employee in each department. It assesses relational reasoning, correct joins, duplicate-name handling, and precise output semantics without assuming a single winner.

The interview report explicitly identified the “Department Highest Salary” SQL exercise. Use the following self-contained PostgreSQL schema:

departments
-----------
department_id  BIGINT  PRIMARY KEY
name           TEXT    NOT NULL

employees
---------
employee_id    BIGINT   PRIMARY KEY
name           TEXT     NOT NULL
salary         NUMERIC  NOT NULL
department_id  BIGINT   NOT NULL REFERENCES departments(department_id)

Write one PostgreSQL query that returns every employee whose salary equals the highest salary in that employee's department.

Return exactly these columns:

  • department: the department name
  • employee: the employee name
  • salary: the employee salary

If several employees tie for the highest salary in a department, return all of them. Departments with no employees do not appear. Do not assume department names or employee names are unique. The relative order of returned rows does not matter.

Find the Highest-Paid Employees in Each Department

Table departments

columntypeconstraints
department_idBIGINTPRIMARY KEY
nameTEXTNOT NULL

Sample data:

department_idname
10Engineering
20Sales
30Research
40Sales
50Operations

Table employees

columntypeconstraints
employee_idBIGINTPRIMARY KEY
nameTEXTNOT NULL
salaryNUMERIC(12,2)NOT NULL
department_idBIGINTNOT NULL, REFERENCES departments(department_id)

Sample data:

department_idemployee_idnamesalary
101Ada120000
102Lin150000
103Noor150000
204Kai90000
205Sam110000
206Sam105000
307Priya130000
408Sam110000
409Mia110000

Expected output

departmentemployeesalary
EngineeringLin150000
EngineeringNoor150000
SalesSam110000
ResearchPriya130000
SalesSam110000
SalesMia110000

Hints

  1. Rank employees within each department rather than across the whole company.
  2. DENSE_RANK with salary descending keeps every employee tied at the maximum.
  3. Join departments only after the per-department salary rank has been computed.