Amazon SQL Interview questions – Leetcode 181 – Employees Earning More Than Their Managers

Problem Description –

The Employee table holds all employees including their managers. Every employee has an Id, and there is also a column for the manager Id.

Given the Employee table, write a SQL query that finds out employees who earn more than their managers. For the above table, Joe is the only employee who earns more than his manager.

Difficulty Level – Easy

Solution –

SELECT
    emp.Name as Employee
FROM employee AS emp JOIN employee AS man
ON emp.ManagerId = man.Id
WHERE emp.Salary > man.Salary

To solve this problem, we need to join the Employee table to itself using a self-join. If we run the following query

SELECT *
FROM employee AS emp JOIN employee AS man
ON emp.ManagerId = man.Id

The output will be –

Here, the left table belongs to the employee and the right table belongs to the managers. And to join the manager table, you need to find a common key in the left table that maches with the manager table that is why we used ON emp.ManagerId = man.Id . Now, if we look at both the row, we can see that Joe is the only employee whose salary ( 70000 ) is greater than his manager’s salary (60000 ). So, to select this employee, we used the emp.Salary > man.Salary in the WHERE clause.

Rating: 1 out of 5.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s