Find Employee's Manager NameMedium

Find Employee's Manager Name

MediumSQLPractice library · +20 XPself joinsqlhierarchy

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