Docs
Docs/JOINs & Relationships/Self Joins

Self Joins

Join a table to itself

A self join is when a table is joined to itself. This is useful for hierarchical or comparative data within the same table.

Example: Employee Hierarchy

employees

idnamemanager_id
1Sarah (CEO)NULL
2John1
3Jane1
4Bob2

Finding Managers

-- Get each employee with their manager's name
SELECT 
    e.name AS employee,
    m.name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id;

-- Result:
-- Sarah | NULL   (CEO has no manager)
-- John  | Sarah
-- Jane  | Sarah
-- Bob   | John

Finding Direct Reports

-- Count direct reports for each manager
SELECT 
    m.name AS manager,
    COUNT(e.id) AS direct_reports
FROM employees m
LEFT JOIN employees e ON m.id = e.manager_id
GROUP BY m.id, m.name
HAVING COUNT(e.id) > 0;

-- Result:
-- Sarah | 2
-- John  | 1

Comparing Within Table

-- Find products more expensive than another product
SELECT 
    p1.name AS product,
    p1.price,
    p2.name AS cheaper_than
FROM products p1
JOIN products p2 ON p1.price > p2.price
WHERE p2.name = 'Basic Plan';

Important: Always use different aliases (e, m) when self-joining to distinguish between the two "copies" of the table.

Need help?

Join our Discord community for support and discussions.

Join Discord