SQL Self Joins
What you will learn
- Why a table sometimes needs to be joined to itself
- How to use two aliases for the same table
- How to join a row to its parent in the same table
- How to find pairs of rows without repeating them
This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). Edit any query and press Run. Reset data puts the original rows back.
1. A table that points to itself
Some tables hold a link to another row of the same table, or you need to compare two rows of one table. The solution is a self join: list the table twice with different aliases, as if there were two copies. The aliases are not optional here; without them SQL could not tell the two copies apart.
The Shop's employees has a manager_id that points to another employee. To show each employee with the name of the manager, join the table to itself: e is the employee, m is the manager.
SELECT e.employee_id, e.name AS employee, e.role, m.name AS manager
FROM employees AS e
LEFT JOIN employees AS m ON m.employee_id = e.manager_id
ORDER BY e.employee_id;
employee_id employee role manager
----------- ------------- -------------- -------------
1 Chen Nguyen Manager NULL
2 Isla Banerjee Sales lead Chen Nguyen
3 Gita Uddin Sales lead Chen Nguyen
4 Mina Kamau Sales Isla Banerjee
5 Yusuf Kumar Sales Isla Banerjee
6 Kofi Bianchi Sales Isla Banerjee
7 Ugo Jensen Sales Gita Uddin
8 Arjun Cohen Sales Gita Uddin
9 Mei Costa Sales Gita Uddin
10 Mina Park Warehouse lead Chen Nguyen
11 Mina Tanaka Warehouse Mina Park
12 Sam Yilmaz Warehouse Mina Park
... (14 rows in total, the first 12 shown)
(It is a LEFT JOIN because the person at the top has no manager, and should still appear.)
The Bank has no table that points to itself, so the first example compares two rows of customers: pairs of different customers who live in the same city. a and b are two copies of the table.
SELECT a.customer_id AS first_customer, b.customer_id AS second_customer, a.city
FROM customers AS a
JOIN customers AS b ON b.city = a.city AND b.customer_id > a.customer_id
ORDER BY a.city, a.customer_id, b.customer_id LIMIT 8;
first_customer second_customer city
-------------- --------------- -----
15 19 Accra
15 33 Accra
15 50 Accra
15 79 Accra
15 96 Accra
15 143 Accra
15 159 Accra
15 193 Accra
(8 rows)
The School has no table that points to itself, so the first example compares two rows of students: pairs of students with the same guardian, who are probably brothers and sisters. a and b are two copies of the table.
SELECT a.student_id AS first_student, a.first_name AS first_name_a,
b.student_id AS second_student, b.first_name AS first_name_b, a.guardian_name
FROM students AS a
JOIN students AS b ON b.guardian_name = a.guardian_name AND b.student_id > a.student_id
ORDER BY a.guardian_name, a.student_id LIMIT 8;
first_student first_name_a second_student first_name_b guardian_name
------------- ------------ -------------- ------------ -------------
1 Vera 171 Rosa Amir Khan
114 Sven 164 Tara Bela Rossi
49 Mei 227 Arjun Chloe Meyer
166 Farid 294 Rina Chloe Nair
24 Chen 258 Arjun Elena Kumar
214 Yusuf 305 Nico Elena Meyer
296 Sara 320 Yusuf Gita Kamau
25 Rosa 84 Chen Grace Kim
(8 rows)
2. Why > in the pair join
In the pair queries the condition b.id > a.id keeps each pair once. Without it every pair would appear twice (A, B and B, A), and every row would also be paired with itself. With > only the combination with the smaller id first survives.
Count the pairs with and without the extra condition to see the effect:
SELECT (SELECT COUNT(*) FROM customers AS a JOIN customers AS b ON b.city = a.city) AS with_duplicates_and_self_pairs,
(SELECT COUNT(*) FROM customers AS a JOIN customers AS b ON b.city = a.city AND b.customer_id <> a.customer_id) AS both_orders,
(SELECT COUNT(*) FROM customers AS a JOIN customers AS b ON b.city = a.city AND b.customer_id > a.customer_id) AS each_pair_once;
with_duplicates_and_self_pairs both_orders each_pair_once
------------------------------ ----------- --------------
5914 5614 2807
(1 row)
SELECT (SELECT COUNT(*) FROM students AS a JOIN students AS b ON b.guardian_name = a.guardian_name) AS with_duplicates_and_self_pairs,
(SELECT COUNT(*) FROM students AS a JOIN students AS b ON b.guardian_name = a.guardian_name AND b.student_id <> a.student_id) AS both_orders,
(SELECT COUNT(*) FROM students AS a JOIN students AS b ON b.guardian_name = a.guardian_name AND b.student_id > a.student_id) AS each_pair_once;
with_duplicates_and_self_pairs both_orders each_pair_once
------------------------------ ----------- --------------
356 34 17
(1 row)
SELECT (SELECT COUNT(*) FROM employees AS a JOIN employees AS b ON b.manager_id = a.manager_id) AS with_duplicates_and_self_pairs,
(SELECT COUNT(*) FROM employees AS a JOIN employees AS b ON b.manager_id = a.manager_id AND b.employee_id <> a.employee_id) AS both_orders,
(SELECT COUNT(*) FROM employees AS a JOIN employees AS b ON b.manager_id = a.manager_id AND b.employee_id > a.employee_id) AS each_pair_once;
with_duplicates_and_self_pairs both_orders each_pair_once
------------------------------ ----------- --------------
39 26 13
(1 row)
Here the pairs are employees with the same manager (colleagues). The people without a manager (NULL) never match, because NULL = NULL is not true (lesson 2.5).
3. A parent in the same table
Another self link: a category and its parent category, a folder and its parent folder.
SELECT c.category_id, c.name AS category, p.name AS parent_category
FROM categories AS c
LEFT JOIN categories AS p ON p.category_id = c.parent_id
ORDER BY c.category_id;
category_id category parent_category
----------- ---------- ---------------
1 Home NULL
2 Kitchen Home
3 Garden Home
4 Office NULL
5 Stationery Office
6 Furniture Office
7 Sport NULL
8 Outdoor Sport
9 Fitness Sport
10 Toys NULL
(10 rows)
The categories without a parent are the top ones. Count the children of each parent:
SELECT p.name AS parent_category, COUNT(c.category_id) AS children
FROM categories AS p
LEFT JOIN categories AS c ON c.parent_id = p.category_id
GROUP BY p.category_id, p.name ORDER BY children DESC, p.category_id;
parent_category children
--------------- --------
Home 2
Office 2
Sport 2
Kitchen 0
Garden 0
Stationery 0
Furniture 0
Outdoor 0
Fitness 0
Toys 0
(10 rows)
The Bank has no parent-child table. Use the self join of the previous section to see the largest groups of customers who share a city:
SELECT a.city, COUNT(DISTINCT a.customer_id) AS customers
FROM customers AS a
JOIN customers AS b ON b.city = a.city AND b.customer_id <> a.customer_id
GROUP BY a.city ORDER BY customers DESC, a.city LIMIT 5;
city customers
----- ---------
Lima 25
Osaka 24
Hanoi 23
Lagos 22
Leeds 22
(5 rows)
The School has no parent-child table. Use the self join to see which guardians have more than one student:
SELECT a.guardian_name, COUNT(DISTINCT a.student_id) AS students
FROM students AS a
JOIN students AS b ON b.guardian_name = a.guardian_name AND b.student_id <> a.student_id
GROUP BY a.guardian_name ORDER BY students DESC, a.guardian_name LIMIT 5;
guardian_name students
------------- --------
Amir Khan 2
Bela Rossi 2
Chloe Meyer 2
Chloe Nair 2
Elena Kumar 2
(5 rows)
(Following a chain of parents to any depth needs a recursive query; see the chapter on CTEs and lesson 3.9 of Database Fundamentals.)
Worked example: who earns more than their manager?
An employees(id, name, salary, manager_id) table. To compare an employee with their manager:
| Step | Do |
|---|---|
| 1 | e is the employee, m is the manager: FROM employees AS e JOIN employees AS m ON m.id = e.manager_id |
| 2 | add the comparison: WHERE e.salary > m.salary |
| 3 | show both names and salaries |
The two aliases let one query refer to two rows of the same table at once. The table is made up (the Shop's employees has a salary column too).
Common mistakes
- Using the table twice without aliases. SQL needs two different names.
- Pairs repeated or paired with themselves. Add
b.id > a.id. - An inner join for a link that can be missing (the top of a hierarchy). Use
LEFT JOIN. - Mixing up the aliases (
e.nameandm.name). - Expecting
NULL = NULLto match.
Key takeaways
- A self join lists one table twice with two aliases.
- A manager or parent link is
JOIN t AS m ON m.id = e.manager_id; useLEFT JOINto keep the top. b.id > a.idkeeps each pair once and no row paired with itself.- Rows with
NULLin the join column never match.
Practice
1. Why does a self join need two different aliases?
Show answer
The same table appears twice, and SQL must be able to tell the two copies apart.
2. Write the join that shows each employee next to their manager's name.
Show answer
FROM employees AS e LEFT JOIN employees AS m ON m.employee_id = e.manager_id, selecting e.name and m.name.
3. What does b.id > a.id do in a pair join?
Show answer
It keeps each pair once and stops a row being paired with itself.
4. Why use LEFT JOIN for the manager link?
Show answer
The person at the top has no manager; a LEFT JOIN keeps that employee with NULL for the manager.
5. Would two employees with no manager be paired by b.manager_id = a.manager_id?
Show answer
No. NULL = NULL is not true, so rows with a NULL manager never match.
6. Which tool follows a parent chain of unknown depth?
Show answer
A recursive query (a recursive CTE), covered later in this course.