All SQL topics
SQL TOPIC

SQL self join: compare rows in the same table

A self join joins a table to itself, for example to put each employee next to their manager.

Use two aliases for the same table: employees e JOIN employees m ON m.id = e.manager_id.

Use LEFT JOIN when some rows have no partner, such as the CEO who has no manager.

Worked example

Who reports to whom?

SELECT e.name AS employee, m.name AS manager
FROM employees e
JOIN employees m ON m.id = e.manager_id
ORDER BY m.name, e.name
LIMIT 6;
Result on the sample data
employeemanager
Ben OkaforAna Costa
Clara NovakAna Costa
David KimAna Costa
Eva LindqvistAna Costa
Farid HaddadBen Okafor
Grace LiuBen Okafor

Common mistakes

  • Reusing one alias for both sides.
  • Using INNER JOIN and losing the rows without a partner.