VillageSQL is a drop-in replacement for MySQL with extensions.
All examples on this page work on VillageSQL. Install Now →
mysql -u root -p sakila before you start.
How a self join works
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 thingsactor 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.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.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.
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 1066is 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
- Table aliases — the naming this query depends on
- INNER JOIN — the join a self join is a special case of
- How joins work — where this sits among the other kinds
- MySQL JOIN performance and common mistakes — what a self join costs on a large table

