Self Join: Comparing Rows Within One Table
Join the employees table to itself to pair each employee with their manager.
Overview
A self join is just an ordinary join where a table is joined to itself,
using different aliases. It's the standard way to model hierarchical or
peer-to-peer relationships stored in a single table — most commonly an
employee/manager relationship where manager_id points back at another
employees.id.
The Query
Employees & Departments
Loading database engine...
Step-by-Step Breakdown
FROM employees e— aliaseis the employee (the "child" side).INNER JOIN employees m ON e.manager_id = m.id— aliasmis the manager (the "parent" side), matched via the foreign keymanager_id.- An
INNER JOINhere excludes top-level staff whosemanager_idisNULL(the department heads). Switch toLEFT JOINto keep them with aNULLmanager.
Keep top-level rows
Use LEFT JOIN employees m instead of INNER JOIN so employees with no
manager (NULL manager_id) still appear, with NULL manager columns.
Variations
Show every employee with their manager, including those without one:
Employees & Departments
Loading database engine...
Common Mistakes
- Reusing the same alias. You must give the table two distinct aliases
(
eandm); referencingemployeestwice without aliases is a syntax error. - Creating a cartesian product. Forgetting the
ON e.manager_id = m.idcondition pairs every employee with every other employee. - Losing top-level rows.
INNER JOINdrops employees whosemanager_idisNULL— often exactly the people (executives) you most want to see.