Before continuing: This entry is part of the JOIN guide. If you are new to the topic, start with JOIN.
SELF JOIN example
| id | name | manager_id |
|---|---|---|
| 1 | Claire Smith | NULL |
| 2 | Alex Reed | 1 |
| 3 | Beth Morgan | 2 |
| 4 | Charles Page | 1 |
| 5 | Diana Lane | 4 |
We want to show each employee along with the name of their manager:
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;| employee | owner |
|---|---|
| Claire Smith | NULL |
| Alex Reed | Claire Smith |
| Beth Morgan | Alex Reed |
| Diana Lane | Charles Page |
Check the result with small data
The same table holds employees and their managers.
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;| employee | owner |
|---|---|
| Amy | NULL |
| Liam | Amy |
| Eva | Amy |
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
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).