01 / 20

SQL Self-Joins

Learn how a single table can be joined with itself to reveal hierarchical relationships and pairwise comparisons hidden within your data.

SQL

What Is a Self-Join?

A self-join is a regular SQL join where a table is joined with itself. You treat the same table as if it were two separate tables by giving each copy a different alias.

SELECT ... FROM table_name AS a JOIN table_name AS b ON a.column = b.column;

Why Use a Self-Join?

Many real-world datasets store relationships within a single table. Self-joins let you unlock these hidden connections without needing extra tables.

Hierarchies
Employees and their managers stored in the same table
Pairwise Comparisons
Find all pairs of students in the same city
Sequential Data
Compare each row with the previous or next row

The Key Ingredient: Aliases

Since both sides of the join reference the same table, SQL needs a way to tell them apart. You must use aliases to give each copy a unique name.

FROM employees AS e -- "the employee" JOIN employees AS m -- "the manager" ON e.manager_id = m.id;

How a Self-Join Works

employees AS e id name mgr_id 1 Alice NULL 2 Bob 1 3 Carol 1 4 Dave 2 employees AS m id name mgr_id 1 Alice NULL 2 Bob 1 3 Carol 1 4 Dave 2 e.mgr_id = m.id Match each employee to their manager

The General Pattern

SELECT a.columns, b.columns FROM table_name AS a JOIN table_name AS b ON a.foreign_key = b.primary_key;
Same table, two aliases
Both FROM and JOIN reference the identical table
ON links the relationship
The ON clause connects a foreign key in one copy to a primary key in the other

Self-Join vs Regular Join

Self-Join Regular Join
Tables involved One table joined with itself Two different tables
Aliases required? Yes (mandatory) Optional but recommended
Use case Rows related to other rows in same table Rows in table A related to rows in table B
SQL syntax INNER, LEFT, RIGHT, FULL, CROSS INNER, LEFT, RIGHT, FULL, CROSS
Example Employee → Manager Order → Customer

INNER vs LEFT Self-Join

INNER JOIN
Only returns employees who have a manager. Rows with NULL manager_id are excluded.
LEFT JOIN
Returns all employees, including those with no manager. The manager columns appear as NULL.
-- Show ALL employees, even the CEO with no manager SELECT e.name AS employee, m.name AS manager FROM employees AS e LEFT JOIN employees AS m ON e.manager_id = m.id;

How to Write a Self-Join

1
Identify the relationship. Which column in a row points to another row in the same table? (e.g., manager_id → id)
2
Write FROM with alias A. Give the "child" or "source" side a short alias like e for employee.
3
JOIN the same table with alias B. Give the "parent" or "target" side a different alias like m for manager.
4
Write the ON clause. Connect the foreign key to the primary key: a.fk = b.pk.
5
SELECT with prefixed columns. Always use alias.column to avoid ambiguity.

Example 1: Employee-Manager

idnamemanager_id
1AliceNULL
2Bob1
3Carol1
4Dave2
SELECT e.name AS employee, m.name AS manager FROM employees AS e LEFT JOIN employees AS m ON e.manager_id = m.id;

Example 2: Pairwise Matching

Find all pairs of students who live in the same city. This is a different pattern: instead of a foreign key, we match rows on a shared attribute.

idnamecity
1MeiAustin
2JordanAustin
3SamDenver
4PriyaAustin
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;

Why \(\texttt{a.id} < \texttt{b.id}\)?

Without the inequality filter, a pairwise self-join produces duplicate and self-matching pairs. The condition \(\texttt{a.id} < \texttt{b.id}\) eliminates both problems.

Without filter
(Mei, Mei), (Mei, Jordan), (Jordan, Mei), (Jordan, Jordan)... duplicates and self-pairs
With \(\texttt{a.id} < \texttt{b.id}\)
(Mei, Jordan), (Mei, Priya), (Jordan, Priya): each unique pair appears exactly once

Example 3: Category Hierarchy

An online store has a categories table where each category can have a parent_id pointing to another category, forming a tree.

idnameparent_id
1ElectronicsNULL
2Phones1
3Laptops1
4Android2
SELECT c.name AS subcategory, p.name AS parent_category FROM categories AS c LEFT JOIN categories AS p ON c.parent_id = p.id;

Two Self-Join Patterns

Hierarchical Pairwise
Relationship Parent-child (FK → PK) Peers sharing an attribute
ON clause \(\texttt{a.fk} = \texttt{b.pk}\) \(\texttt{a.attr} = \texttt{b.attr} \text{ AND } \texttt{a.id} < \texttt{b.id}\)
Join type LEFT JOIN (include NULLs) INNER JOIN (only matches)
Example Employee → Manager Student pairs in same city
Duplication risk Low High without \(\texttt{a.id} < \texttt{b.id}\) filter

Common Mistakes

✕ Forgetting Aliases
Without aliases, SQL raises an "ambiguous column name" error because it cannot tell which copy of the table you mean.
✕ Missing the \(\texttt{a.id} < \texttt{b.id}\) Filter
In pairwise joins, omitting \(\texttt{a.id} < \texttt{b.id}\) produces duplicate pairs and self-matches, inflating your results.
✕ Using INNER Instead of LEFT
For hierarchies, INNER JOIN silently drops rows with NULL foreign keys (e.g., the CEO with no manager).

Question 1 of 5

What makes a join a "self-join"?

Question 2 of 5

Given this query, what role does alias m represent?

SELECT e.name, m.name FROM employees AS e JOIN employees AS m ON e.manager_id = m.id;

Question 3 of 5

In a pairwise self-join, why do we add the condition \(\texttt{a.id} < \texttt{b.id}\)?

Question 4 of 5

The CEO has manager_id = NULL. Which join type ensures the CEO still appears in the results?

Question 5 of 5

What happens if you write a self-join without using aliases?