Find Employee's Manager Name
A company database stores employee information, including who their manager is. Each employee has a unique employee ID, their name, and the employee ID of their manager (if they have one). Some employees might not have a manager (e.g., the CEO).
Table: employees
employee_id(integer, primary key)name(varchar(100))manager_id(integer, can be NULL)
Return the employee_id, name of the employee, and the name of their manager. The output should be ordered by employee_id.
If an employee has no manager, their manager's name should be displayed as 'No Manager'. Handle NULL manager IDs correctly. If the result set is empty, return an empty set.
Tables
CREATE TABLE employees (
employee_id integer PRIMARY KEY,
name varchar(100) NOT NULL,
manager_id integer
);Example data
INSERT INTO employees (employee_id, name, manager_id) VALUES (1, 'Alice', NULL), (2, 'Bob', 1), (3, 'Charlie', 1), (4, 'David', 2), (5, 'Eve', 3), (6, 'Frank', 3), (7, 'Grace', 4);
Your query is also checked on hidden datasets with different data.
Hints
Similar problems
- Find Employees With No Direct ReportsMedium
- Find Students with Above-Average GPA in Their DepartmentMedium
- Students with Above Average GPA in Their DepartmentMedium
- Organizational Hierarchy with TenureHard
- Internship Offers by Department and SalaryMedium
- Dishes Present in Only One Cuisine TypeMedium
More in: SQL and Databases problems
-- Select employee and manager names
SELECT
Your query runs on the example tables shown with the problem, then on hidden datasets when you submit.
Write standard SQL. MySQL habits work too: IFNULL, IF, YEAR(), DATE_FORMAT, GROUP_CONCAT, `backticks` and LIMIT 5, 10. It runs on PostgreSQL, so integer division keeps whole numbers (5 / 2 = 2): write 5.0 / 2 for 2.5.