Sometimes the rows you want to connect live in the same table. Each employee row stores a manager_id, and the manager is just another employee in that table. Two students in the same city are two rows of the same students table. To compare or connect rows like these, you join a table to itself. This is called a self join.
In this lesson you will learn
- Why a self join needs two table aliases
- How to show each employee with their manager
- Why
LEFT JOINkeeps the person at the top - How to find pairs of rows without duplicates
- How to compare a row with a related row
You should know SQL joins.
One Table, Two Roles
SQL has no special keyword for a self join. You write an ordinary join, but list the same table twice with two different aliases. Each alias plays a different role. Below, e is the employee and m is the manager.
-- Each employee with the name of their manager
SELECT e.name AS employee,
e.title,
m.name AS manager
FROM employees AS e
LEFT JOIN employees AS m ON m.id = e.manager_id
ORDER BY e.id;
Output
+----------+------------+---------+
| employee | title | manager |
+----------+------------+---------+
| Shahana | CEO | NULL |
| Faisal | CTO | Shahana |
| Lipi | CFO | Shahana |
| Rubel | Engineer | Faisal |
| Mou | Engineer | Faisal |
| Anik | Accountant | Lipi |
| Sumi | Intern | Rubel |
+----------+------------+---------+
(7 rows)
- The join condition
m.id = e.manager_idsays: the manager row is the one whoseidequals this employee’smanager_id. - Shahana is the CEO, so her
manager_idis NULL.LEFT JOINkeeps her with a NULL manager. An innerJOINwould drop her. - Without aliases, SQL could not tell which copy of
employeesa column belongs to.
Finding Pairs
-- Pairs of students who live in the same city
SELECT a.name AS student_1,
b.name AS student_2,
a.city
FROM students AS a
JOIN students AS b
ON a.city = b.city
AND a.id < b.id -- each pair once, never a student with themselves
ORDER BY a.city, a.name;
-- Employees who earn at least half of their manager's salary
SELECT e.name, e.salary, m.name AS manager, m.salary AS manager_salary
FROM employees AS e
JOIN employees AS m ON m.id = e.manager_id
WHERE e.salary * 2 >= m.salary
ORDER BY e.salary DESC;
Output
+-----------+-----------+------------+
| student_1 | student_2 | city |
+-----------+-----------+------------+
| Arif | Nadia | Chattogram |
| Nusrat | Rafi | Dhaka |
| Nusrat | Tania | Dhaka |
| Tania | Rafi | Dhaka |
+-----------+-----------+------------+
(4 rows)
+--------+--------+---------+----------------+
| name | salary | manager | manager_salary |
+--------+--------+---------+----------------+
| Faisal | 180000 | Shahana | 250000 |
| Lipi | 170000 | Shahana | 250000 |
| Mou | 95000 | Faisal | 180000 |
| Rubel | 90000 | Faisal | 180000 |
+--------+--------+---------+----------------+
(4 rows)
a.city = b.citymatches students in the same city.a.id < b.iddoes two jobs. It stops a student pairing with themselves, and it lists each pair once. With<>instead, you would get both Nusrat–Tania and Tania–Nusrat.- The second query compares each employee’s salary with their manager’s salary, which sit in two different rows.
Common Uses
| Question | Join condition |
|---|---|
| Who is each person’s manager? | m.id = e.manager_id |
| Which customers live in the same area? | a.area = b.area AND a.id < b.id |
| Which bookings overlap? | a.room = b.room AND a.start < b.finish AND b.start < a.finish |
| Which products cost more than another in the same category? | a.category = b.category AND a.price > b.price |
For a chain of many levels, such as the whole management tree, use a recursive query instead of joining the table again and again. To compare a row with the row just before it in time, LAG and LEAD are usually simpler.
Common Mistakes
- Forgetting the aliases.
employees JOIN employeesis ambiguous; give each copy a name. - Using
<>for pairs. Every pair appears twice. Use<. - Using an inner join for a hierarchy. The top person, with no manager, disappears.
- Mixing up the direction.
e.id = m.manager_idgives each manager’s reports, not each employee’s manager.
Practice Exercises
Exercise 1. List each manager with the number of people who report directly to them.
Show answer
SELECT m.name AS manager, COUNT(*) AS direct_reports
FROM employees AS e
JOIN employees AS m ON m.id = e.manager_id
GROUP BY m.id
ORDER BY direct_reports DESC;
Shahana and Faisal have 2 each; Lipi and Rubel have 1.
Exercise 2. Find pairs of students in the same department where the first has a higher CGPA than the second.
Show answer
SELECT a.name AS higher, b.name AS lower, a.dept
FROM students AS a
JOIN students AS b ON a.dept = b.dept AND a.cgpa > b.cgpa;
Rows with a NULL CGPA never match, because comparisons with NULL are unknown.
Frequently Asked Questions
What is a self join in SQL?
A self join joins a table to itself. You list the same table twice with different aliases, such as e for employee and m for manager, and join them on a condition that links two rows of that table.
How do I avoid duplicate pairs in a self join?
Add a condition such as a.id < b.id. It removes a row being paired with itself and keeps only one order of each pair, so A with B appears but B with A does not.
Summary
- A self join lists one table twice with two aliases, each playing a different role.
- Use
LEFT JOINfor hierarchies so the top row is kept. - Use
a.id < b.idto get each pair once. - For deep hierarchies use recursive queries; for “previous row” use LAG.
