SQLMediumJoins20 min

Show employees and their grandmanagers

Return every employee ID, employee name, manager name, and grandmanager name. Preserve employees without a manager or grandmanager and show missing names as NULL. Return only the requested columns and follow the specified ordering. This question probes two left self joins traverse exactly two reporting edges while preserving incomplete chains.

Input

Setup script defining employees(id INT, name VARCHAR(30), department_id INT, manager_id INT, salary INT).

Output

id, employee_name, manager_name, grandmanager_name; ascending employee ID.

Constraints

0–10000 rows per table. IDs are unique and non-NULL unless stated otherwise; foreign keys may be NULL. Numeric amounts are integers from 0 to 1000000. Dates are valid YYYY-MM-DD text. Text uses case-sensitive comparison; test data has consistent case. Duplicate business values and NULLs are allowed unless excluded by the task.

Example

Tables and sample rows

CREATE TABLE employees(id INT, name VARCHAR(30), department_id INT, manager_id INT, salary INT);
INSERT INTO employees VALUES (1,'Ana',10,NULL,100),(2,'Ben',10,1,200),(3,'Cara',20,1,200),(4,'Dan',20,3,300),(5,'Eve',NULL,NULL,NULL);

Expected result

id | employee_name | manager_name | grandmanager_name
1 | Ana | NULL | NULL
2 | Ben | Ana | NULL
3 | Cara | Ana | NULL
4 | Dan | Cara | Ana
5 | Eve | NULL | NULL

Another dataset (1)

CREATE TABLE employees(id INT, name VARCHAR(30), department_id INT, manager_id INT, salary INT);
INSERT INTO employees VALUES (1,'Solo',10,NULL,100),(2,'Twin',10,1,100),(3,'Null',NULL,NULL,NULL);

Expected result

id | employee_name | manager_name | grandmanager_name
1 | Solo | NULL | NULL
2 | Twin | Solo | NULL
3 | Null | NULL | NULL

Covers missing matches, ties, or NULL values without relying on insertion order.

Hints (2)
  1. Use a separate alias for each hierarchy level.
  2. Both joins must be LEFT JOINs.

Target complexity: time O(n^2) · space O(n)

Your query

Checked instantly on your device with SQLite against 2 datasets. Rows must match the expected columns and order.

Reference solution

Sign in for solution
All SQL queries