A self join joins a table to itself using two aliases. It's how you relate rows within one table — an employee to their manager, a product to a related product.
Employee → manager
SELECT e.name AS employee, m.name AS managerFROM employees eLEFT JOIN employees m ON e.manager_id = m.id;-- LEFT JOIN so the CEO (no manager) still appears
Key takeaways
- 01A self join joins a table to itself using two different aliases.
- 02It models within-table relationships: employee/manager, parent/child.
- 03Use LEFT JOIN for hierarchies so the top (parent-less) row stays.
- 04Self joins can also find pairs of rows sharing an attribute.
