Self Join in SQL: A Step-by-Step Guide

Join a table to itself to compare rows within the same dataset.

A self join is simply a regular join where a table is joined to itself. It looks unusual the first time you see it, but it solves a very common problem: comparing rows within the same table.

Step 1: Identify the Relationship

Self joins are used when one row in a table references another row in the same table — the classic example is an employees table where each employee has a manager_id that points to another employee's id.

Step 2: Alias the Table Twice

Since you're joining a table to itself, you need two different aliases to distinguish the two "copies."

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

Step 3: Choose the Right Join Type

Use LEFT JOIN instead of JOIN if you also want to see employees who have no manager assigned (like the CEO):

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

Step 4: Add Filters if Needed

SELECT e.name AS employee, m.name AS manager
FROM employees e
JOIN employees m ON e.manager_id = m.id
WHERE m.department = 'Engineering';
💡 Tip: If your query returns unexpectedly large results, double check your join condition — a missing or incorrect condition can accidentally produce a cross join.

Common Use Cases

  • Employee-manager hierarchies
  • Finding duplicate records within the same table
  • Comparing rows, like matching products with the same price

Seeing the Result on Real Rows

It is much easier to understand a self join when you can see the input and output side by side. Take this small employees table:

idnamemanager_iddepartment
1KavitaNULLManagement
2Arjun1Engineering
3Meera1Sales
4Rohit2Engineering
5Sana2Engineering

Running the LEFT JOIN version from Step 3 gives:

employeemanager
KavitaNULL
ArjunKavita
MeeraKavita
RohitArjun
SanaArjun

For each row in e, the database looks for a row in m whose id equals e.manager_id. Kavita has no manager id, so the inner join drops her while the left join keeps her with a NULL.

Finding Duplicates and Pairs Without Double Counting

A self join can compare every row with every other row that shares a value. The trick is an extra condition that stops a row from matching itself and stops each pair from appearing twice.

-- Customers registered more than once with the same email
SELECT a.id AS first_id, b.id AS duplicate_id, a.email
FROM customers a
JOIN customers b
  ON a.email = b.email
 AND a.id < b.id;

-- Colleagues in the same department, each pair listed once
SELECT a.name AS person_1, b.name AS person_2, a.department
FROM employees a
JOIN employees b
  ON a.department = b.department
 AND a.id < b.id;

Using a.id < b.id rather than a.id <> b.id is the key detail. With <> you would get both (Rohit, Sana) and (Sana, Rohit).

Counting direct reports

SELECT m.name AS manager, COUNT(e.id) AS direct_reports
FROM employees m
LEFT JOIN employees e ON e.manager_id = m.id
GROUP BY m.id, m.name
ORDER BY direct_reports DESC;

Counting e.id instead of * makes people with no reports show zero rather than one.

When a Recursive CTE Is the Better Tool

A self join reaches exactly one level per join. Finding a manager's manager needs a second join, and an unknown number of levels needs a recursive common table expression, supported in MySQL 8 and later, PostgreSQL and SQL Server:

WITH RECURSIVE chain AS (
    SELECT id, name, manager_id, 0 AS level
    FROM employees
    WHERE id = 4                      -- start from Rohit
    UNION ALL
    SELECT e.id, e.name, e.manager_id, c.level + 1
    FROM employees e
    JOIN chain c ON e.id = c.manager_id
)
SELECT name, level FROM chain;

SQL Server uses the same idea but writes WITH chain AS without the RECURSIVE keyword.

Performance and Accuracy Checklist

  • Index the column used in the join condition, such as manager_id, so lookups stay fast on large tables.
  • Use clear aliases like e and m, or emp and mgr, so nobody mixes up the two copies.
  • Decide up front whether rows without a match should appear, and choose INNER or LEFT JOIN accordingly.
  • Add an inequality on the key when comparing rows with each other, to avoid self-matches and mirrored pairs.
  • Check the row count against your expectation; a sudden jump usually means a loose join condition.

Ready to go beyond the basics?

Get hands-on training, live mentorship, and placement support with Uncodemy's Data Analytics Course.

Explore Data Analytics Course →