The Employees Earning More Than Their Managers interview question is a classic SQL problem. You are given an Employee table that contains employee names, their salaries, and the ID of their manager (who is also an employee in the same table). Your task is to write a query that identifies all employees who have a higher salary than their direct manager.
This is a staple database interview pattern asked by companies like Microsoft, Amazon, and Google to test a candidate's understanding of Self-Joins. It evaluates whether you can compare rows within the same table by joining the table to itself. It also tests basic filtering skills using the WHERE clause and the ability to distinguish between the two instances of the table being joined.
The problem is solved using a Self-Join.
Employee table twice (e.g., e for employee and m for manager).e.managerId = m.id.e.salary > m.salary.Suppose the Employee table has:
e.id = m.managerId, which would find managers earning more than their employees.managerId is NULL) will automatically be excluded by an INNER JOIN.Whenever you need to compare records within the same table based on a hierarchical or parent-child relationship, a Self-Join is your go-to tool. Practice assigning clear aliases to the table instances to keep your logic organized.