SQL self join
A self join joins a table to itself. It is used for hierarchies (employees and their managers) and for comparing rows within the same table.
The trick is to give the table two different aliases and treat them as two separate tables.
Syntax
SELECT e.name, m.name FROM employees e JOIN employees m ON m.id = e.manager_id;
Try it yourself
Run the example below on a real PostgreSQL database, then change it and run it again. Nothing to install, no sign-up.
self-join.sql · PostgreSQL
Loading editor…
Examples
1. Employees and managers
SELECT e.first_name AS employee, m.first_name AS manager FROM employees e JOIN employees m ON m.id = e.manager_id;
Every employee with a manager.
Common mistakes
- Using the same alias twice, or forgetting which alias is the manager.
Practice: test yourself
This challenge is from our interactive course. Write the query and press Check answer.
Challenge · 30 pts
For each employee who has a manager, return the employee's first_name and the manager's first_name.
challenge.sql · PostgreSQL
Loading editor…
FAQ
How do I include people without a manager?
Use LEFT JOIN instead of JOIN.
Learn SQL step by step
65 hands-on exercises, streaks, a leaderboard and a certificate.