SQL · Level 2 Joins

SQL Self Join

Show every employee with their manager by joining the employees table to itself, without losing the boss who has no manager.

  • Two aliases, one table
  • LEFT JOIN for missing parents
  • COALESCE() replaces NULL

A table can join to itself: an employee's manager is another employee. Give each copy its own alias. Trap: an inner join drops the boss, who has no manager; use LEFT JOIN, and COALESCE(x, 'none') to replace the NULL.

SELECT c.name, COALESCE(p.name, 'top level') AS parent
FROM categories AS c
LEFT JOIN categories AS p ON p.id = c.parent_id;

Return each employee's name and their manager's name, with 'none' for someone without a manager, ordered by employee name. In the database below, Ada is the boss.

Sample data from the first test. The other tests use different rows, so write a query, not a list of answers.

employees 4 rows
idINTEGERnameTEXTmanager_idINTEGER
1AdaNULL
2Ben1
3Cleo1
4Dan2
solution.sql
Test Suites Pending
Output