73. Orphan Employees

In an employee management system, when a manager leaves the company, their record is deleted, but their direct reports still have their manager_id set to that person.

You are given the Employees table with the following columns:

╔══════════════╦════════╦════════════╦════════╗
β•‘ employee_id  β•‘ name   β•‘ manager_id β•‘ salary β•‘
╠══════════════╬════════╬════════════╬════════╣
β•‘ int          β•‘ varcharβ•‘ int        β•‘ int    β•‘
β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•
  • employee_id: Unique ID of the employee
  • name: Employee’s name
  • manager_id: ID of the employee’s manager (can be NULL)
  • salary: Salary of the employee

Write an SQL query to find the employee_ids of all employees whose salary is less than 30000 and whose manager left the company (i.e., manager_id not found in the list of current employee_ids). Return the result sorted by employee_id.

Example 1:

Example:

Employees Table:
╔══════════════╦════════════╦════════════╦════════╗
β•‘ employee_id  β•‘ name       β•‘ manager_id β•‘ salary β•‘
╠══════════════╬════════════╬════════════╬════════╣
β•‘ 3            β•‘ Mila       β•‘ 9          β•‘ 60301  β•‘
β•‘ 12           β•‘ Antonella  β•‘ null       β•‘ 31000  β•‘
β•‘ 13           β•‘ Emery      β•‘ null       β•‘ 67084  β•‘
β•‘ 1            β•‘ Kalel      β•‘ 11         β•‘ 21241  β•‘
β•‘ 9            β•‘ Mikaela    β•‘ null       β•‘ 50937  β•‘
β•‘ 11           β•‘ Joziah     β•‘ 6          β•‘ 28485  β•‘
β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•

Output:

╔═════════════╗
β•‘ employee_id β•‘
╠═════════════╣
β•‘ 11          β•‘
β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•

Explanation:

  • Kalel (1): salary < 30000, manager_id = 11 β†’ still exists β†’ Excluded
  • Joziah (11): salary < 30000, manager_id = 6 β†’ does not exist β†’ Included

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Hints

0
Β 
Test Case

Input:

Employees