← Back to PostgreSQL Course | Chapter 6: Joins | Lesson 6 of 7

Self JOIN

A self join joins a table to itself, using aliases to treat it as two tables.

In this page:

  1. Self JOIN
Syntax
sql
SELECT a.column, b.column
FROM table_name a
JOIN table_name b ON a.foreign_key = b.id;

Self JOIN

The classic use is an employee table with a manager_id column pointing to another row in the same table.

Give the table two aliases and join them. Use LEFT JOIN to keep employees without a manager, such as the CEO.

Recursive queries handle multi-level hierarchies.

Note: Different aliases for the same table are what make a self join possible.

Example: Self JOIN

sql
CREATE TABLE staff (id INTEGER PRIMARY KEY, name TEXT, manager_id INTEGER);
INSERT INTO staff VALUES (1, 'Ada', NULL), (2, 'Bob', 1), (3, 'Cy', 1), (4, 'Di', 2);
SELECT e.name AS employee, m.name AS manager FROM staff e LEFT JOIN staff m ON e.manager_id = m.id ORDER BY e.id;

-- Output:
-- employee | manager
-- Ada | NULL
-- Bob | Ada
-- Cy | Ada
-- Di | Bob
Related Topics
Common Mistakes
  1. Forgetting aliases
  2. Using INNER JOIN and losing the top of the hierarchy
  3. Confusing the two roles of the table
Chapter Summary
  • Join a table to itself
  • Use two aliases
  • LEFT JOIN keeps top-level rows
  • Recursive CTEs do deeper hierarchies
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.