SELF JOIN: A table joined to itself, using aliases, to relate rows within the same table (e.g. employee → manager). A self join joins a table to itself, using two different aliases. It relates rows within the same table, such as each employee to their manager, who is also stored in the employees table.
SELECT e.name, m.name AS manager FROM employees e LEFT JOIN employees m ON e.manager_id = m.id lists every employee with the name of their manager.
What should you keep in mind with SELF JOIN?
Self joins also help to compare rows, such as finding pairs of customers with the same email address or orders placed within a minute of each other. Use a LEFT JOIN when some rows have no match, like the director without a manager. For deeper hierarchies, such as a whole organisation chart or nested categories, a recursive CTE is the better tool.
What does an example of SELF JOIN look like?
SELECT e.name, m.name AS manager FROM employees e JOIN employees m ON e.manager_id = m.id;