Self JOIN in SQL
Level 4154 keystrokes
A self JOIN joins a table to itself; two aliases let one copy act as the employee and the other as the manager.
SQL code
-- Return the employee's name and their manager's name1SELECT2 e.name AS employee,3 m.name AS manager4FROM -- Alias e: the employees table seen as employees5 employees e-- Join the same table again as m (the managers), linking manager_id to id6LEFT JOIN7 employees m ON e.manager_id = m.id-- Drop employees with no manager_id (e.g. the boss), so LEFT JOIN keeps nothing extra here8WHERE9 e.manager_id IS NOT NULL-- Sort by manager name10ORDER BY11 m.name;Output
+----------+---------+ | employee | manager | +----------+---------+ | Bob | Alice | | Carol | Alice | | Dave | Bob | +----------+---------+ 3 rows in set
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this SQL code and how often they appear.
.× 6_× 2,× 1;× 1=× 1