Chapter 6 · Lesson 6 of 7

SELF JOIN for Hierarchies

Join a table to itself with table aliases to model a hierarchy, and list each employee next to their manager's name.

A self join joins a table to itself. This is common when rows relate to other rows in the same table, such as employees and managers.

SELECT e.name AS employee_name, m.name AS manager_name
FROM employees AS e
LEFT JOIN employees AS m
  ON e.manager_id = m.id

The employees table appears twice with different aliases. One copy represents the employee, and the other represents the manager.

This pattern is useful for org charts, parent-child relationships, and tree-like data.

Sample data

This lesson loads the employees + departments tables into DuckDB in your browser with one click, so you can run every example without uploading anything.

Setup SQL for employees, departments
CREATE OR REPLACE TABLE departments (
    id INTEGER,
    name VARCHAR
  );

INSERT INTO departments VALUES
    (1, 'Engineering'),
    (2, 'Marketing'),
    (3, 'Sales'),
    (4, 'Support');

CREATE OR REPLACE TABLE employees (
    id INTEGER,
    name VARCHAR,
    department_id INTEGER,
    manager_id INTEGER
  );

INSERT INTO employees VALUES
    (1, 'Alice', 1, NULL),
    (2, 'Bob', 2, 1),
    (3, 'Charlie', 1, 1),
    (4, 'Diana', 3, 2),
    (5, 'Eve', NULL, 2),
    (6, 'Frank', 1, 3);

Practice challenge

List every employee together with their manager. Return employee_name and manager_name, ordered by employee_name. Include Alice with a NULL manager_name.

Hint: Join employees to itself with two aliases, and use a LEFT JOIN so Alice still appears.

Run your query in the editor and the lesson checks the result automatically.

Open this lesson in the SQL editor

Lessons in JOIN Types

Combine related tables with INNER, LEFT, RIGHT, FULL OUTER, SELF, and CROSS JOIN, and find rows that have no match.

  1. 01 · Why JOINs Exist
  2. 02 · INNER JOIN Basics
  3. 03 · LEFT JOIN Keeps the Left Side
  4. 04 · Finding Missing Matches
  5. 05 · RIGHT JOIN and FULL OUTER JOIN
  6. 06 · SELF JOIN for Hierarchies
  7. 07 · CROSS JOIN for All Combinations

Related guides