MySQL Self Join
MySQL Self Join: Joining a Table to Itself
A MySQL self join joins a table back to itself so you can compare rows inside the same table or traverse parent-child hierarchies. You implement a self join using standard INNER JOIN or LEFT JOIN syntax with two different aliases for the same table.
Basic Syntax
Assign distinct aliases (such as e for employee and m for manager) so MySQL knows which side of the relationship each column belongs to:
SELECT
child.column_name,
parent.column_name AS parent_name
FROM table_name AS child
LEFT JOIN table_name AS parent
ON child.parent_id = parent.id;
Practical SQL Example
Suppose demo_employees has a manager_id column referencing demo_employees.id. A LEFT JOIN shows every staff member along with their manager's name (keeping top executives whose manager_id is NULL):
SELECT
e.id AS employee_id,
e.full_name AS employee_name,
COALESCE(m.full_name, 'Top Executive') AS manager_name
FROM demo_employees AS e
LEFT JOIN demo_employees AS m
ON e.manager_id = m.id
ORDER BY e.id ASC;
| employee_id | employee_name | manager_name |
|---|---|---|
| 1 | Elena Brooks | Top Executive |
| 2 | Maya Patel | Elena Brooks |
| 3 | Liam Chen | Maya Patel |
Common Mistakes and Best Practices
- Use
LEFT JOINfor Root Nodes: UsingINNER JOINdrops the CEO or root category because itsmanager_idisNULL. UseLEFT JOINwhenever root rows must stay visible. - Avoid Duplicate Pairs in Peer Comparisons: When finding pairs of customers in the same city (
FROM demo_customers a INNER JOIN demo_customers b ON a.city = b.city), addAND a.id < b.idso you do not match each row to itself or return(A, B)and(B, A)twice. - Switch to Recursive CTEs for Deep Trees: A self join handles one parent level cleanly; for multi-level org charts of unknown depth, use
WITH RECURSIVEin MySQL 8.
Frequently Asked Questions
Is there a SELF JOIN keyword in MySQL?
No, a self join is simply an INNER JOIN or LEFT JOIN where both sides reference the same table under different aliases.
Why are table aliases mandatory in a self join?
Without distinct aliases, MySQL cannot tell whether manager_id or id refers to the employee copy or the manager copy of the table.
Can a self join update rows in the same table?
Be careful: MySQL blocks UPDATE or DELETE when a subquery references the same target table directly unless wrapped cleanly in an explicit JOIN.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.