Self-Joins

A table joined to itself, so a row can be compared against another row of the same kind. Employees and their managers, twice over.

Self-Joins

What a self-join can answer

query.sql SQLite
Result

Worth knowing

There is nothing special about the syntax. It is an ordinary join where both sides happen to name the same table.
Aliases stop being optional. Without e and m there is no way to say which name you mean.
An inner self-join silently drops the top of a hierarchy, because the root's parent is NULL. LEFT JOIN keeps it.
a.id < b.id in the join condition turns every unordered pair from two rows into one.

Overview

An employee table may include both an employee ID and a manager ID. To show each employee beside their manager's name, join the table to itself and assign each copy a clear alias.

In this guide
  1. One table, two roles
  2. Compare rows within a table
  3. Avoid common self-join mistakes
  4. Pair each unordered relationship once
  5. Use a self-join for one-level relationships
  6. Further reading

One table, two roles

query.sqlSQLite
Result

The aliases name the roles: e is the employee row and m is the referenced manager row. The left join keeps employees who have no manager, such as a top-level executive.

Compare rows within a table

Self-joins can find pairs such as products in the same category or rows whose date ranges overlap. The join condition determines which pairs appear. For unordered pairs, use a strict condition like a.id < b.id; using a.id <> b.id returns both (A, B) and (B, A).

The number of output rows can grow quickly when many rows match. Check uniqueness and cardinality before aggregating the result. If the problem is variable-depth traversal through a hierarchy, a recursive CTE may be more suitable.

Avoid common self-join mistakes

Joining each row to itself can create a trivial match; exclude it if the question needs distinct rows. Ambiguous column names are another risk, so qualify columns with aliases. A LEFT JOIN becomes effectively inner if a condition on the right alias is placed in WHERE and rejects NULLs; put match restrictions in ON when unmatched left rows must remain. See joins.

Pair each unordered relationship once

To find pairs of coworkers in the same team, joining on equal team IDs matches each person with themselves and returns both directions of every pair. Add a.id < b.id to exclude self-pairs and keep only one orientation. If the question instead concerns ordered relationships, such as employee and manager, do not impose that condition; use the directional foreign key. The pair condition encodes the meaning of the result, so state whether (A, B) differs from (B, A) before choosing it.

Use a self-join for one-level relationships

A manager lookup is a one-level relationship: each employee row points to at most one manager row. For a chain of managers several levels above an employee, a single self-join only reaches the number of levels explicitly written. Use a recursive CTE when depth is variable. A self-referencing foreign key can ensure the manager ID exists, but it does not necessarily prevent a person from becoming their own manager or creating a longer cycle; those are separate integrity rules.

Further reading

Check yourself

0 of 3

Answer without scrolling back up.

  1. Why does an inner self-join drop the top of a hierarchy?

  2. Why is `a.id < b.id` preferred over `a.id <> b.id` when pairing rows?

  3. When does a self-join stop being the right tool?

Cheat sheet

Self-Joins

Join a table to itself, match employees to managers in the same rows, and walk through the three query patterns that need a self-join.

DATABASE · vizlearn.in/database/self_joins_in_sql.html

About the author

Ashish Jangra builds and maintains VizLearn. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.

Teaching a course with this? Individual teachers can use it freely; for a whole department or programme, see institutional licences.