Concept · Combining tables

SELF JOIN

A SELF JOIN joins a table to itself. It uses two aliases to tell their roles apart, such as employee and manager.

Before continuing: This entry is part of the JOIN guide. If you are new to the topic, start with JOIN.

SELF JOIN example

Employee rows used
idnamemanager_id
1Claire SmithNULL
2Alex Reed1
3Beth Morgan2
4Charles Page1
5Diana Lane4

We want to show each employee along with the name of their manager:

SQL
SELECT e.name AS employee,
       r.name AS owner
FROM employees AS e
LEFT JOIN employees AS r
  ON e.manager_id = r.id
WHERE e.id IN (1, 2, 3, 5)
ORDER BY e.id;
Expected result
employeeowner
Claire SmithNULL
Alex ReedClaire Smith
Beth MorganAlex Reed
Diana LaneCharles Page

Check the result with small data

The same table holds employees and their managers.

Self-contained query · SQLite
WITH employees(id, name, manager_id) AS (
  VALUES (1,'Amy',NULL), (2,'Liam',1), (3,'Eva',1)
)
SELECT e.name AS employee, j.name AS owner
FROM employees e LEFT JOIN employees j ON e.manager_id=j.id
ORDER BY e.id;
Query result
employeeowner
AmyNULL
LiamAmy
EvaAmy

employees is used twice with different aliases. Amy has no manager, while Liam and Eva both report to Amy.

Check your understanding: What would we lose if the JOIN were not a LEFT JOIN?

Show answer

Amy: with an INNER JOIN her manager_id is NULL, she finds no match and would disappear from the result.

Common mix-ups with SELF JOIN

Not telling the two instances apart

Problem query
SELECT name, name
FROM employees
JOIN employees
  ON manager_id = id;

The table and column names become ambiguous. Assign clear aliases and qualify every column: e.name, r.name, e.manager_id and r.id.

A hierarchy does not always fit in a single join

A SELF JOIN does not create a persistent copy of the table. Each alias represents a role within the query: one person acts as the employee and another as the manager. Read the condition in terms of those roles: the manager's id must match the reference stored in the employee's row. Comparing the two rows' own ids would only pair each person with themselves.

If you also want the people who have no manager, keep the employee side with an outer join. An INNER JOIN drops those people. A reference to a manager who does not exist also produces no match; to tell it apart from an unassigned manager, show the requested id alongside the id that was found. A foreign key helps prevent broken references, but on its own it does not express every rule of a hierarchy.

The example query goes down one level. It does not automatically return the manager's manager or every ancestor. For a variable depth you need a recursive approach and a decision about what to do with cycles. Check separately a person at the top, a person with a manager, and two people with the same manager: sharing a manager should produce two employee rows, not a single grouped row.

Technical questions: PostgreSQL: Table Expressions and Joins (opens in a new tab).