Skip to main content

VillageSQL is a drop-in replacement for MySQL with extensions.

All examples on this page work on VillageSQL. Install Now →
A self join reads 1 table twice in the same query, so you can compare its rows against each other. It is how you answer questions about pairs: which rows share a value, which row is bigger than which. Open the client with mysql -u root -p sakila before you start.

How a self join works

Replace TABLE_NAME with the table, FIRST_ALIAS and SECOND_ALIAS with 2 different names for it, and each COLUMN_NAME with the column being compared. Nothing else about the join changes. The server has no idea the 2 sides are one table, and treats them as it would any other pair.

The aliases are not optional

Without them the query names 2 things actor and cannot tell them apart.
ERROR 1066 is the server saying it needs a name for each side.

Examples

1) Rows that share a value

Some Sakila actors share a surname. This pairs each of them with the others.
3 actors are called AKROYD, which makes 3 pairs among them.

2) Compare rows on a number

The same shape answers “which films run exactly as long as which”. This narrows it to the longest films in the catalog.
10 films run 185 minutes, and 45 is the number of pairs you can make from 10 things.

What the second condition is doing

a1.actor_id < a2.actor_id is what keeps each pair once and keeps an actor from pairing with themselves. Take it out and the same query answers something else.
416 rows instead of 108, and 2 kinds of row have crept in. CHRISTIAN AKROYD is paired with himself, because his own row satisfies a1.last_name = a2.last_name. And CHRISTIAN with DEBBIE appears, then DEBBIE with CHRISTIAN, which is the same pair written backwards. Comparing the ids with < fixes both at once. It rules out the row matching itself, because no id is less than itself, and it keeps only 1 arrangement of each genuine pair. Use < whenever a self join is looking for pairs.

Summary

  • Use a self join to compare the rows of 1 table against each other.
  • Give the table 2 aliases, because ERROR 1066 is what you get without them.
  • Compare the 2 aliases’ primary keys with < when you want each pair once.
  • Expect a row to match itself if you do not rule it out.

See also