SQL Self Join (Self-join)

SQL Self Join Description

A self-join is a regular join where a table is joined to itself.

Self Join Syntax

SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition

T1 and T2 are different aliases for the same table.

Demonstration database

In this tutorial we will use the famous example database "Northwind".

Below is a sample from the table "Customers" ("Customers").

1Alfreds FutterkisteMaria AndersObere Str. 57Berlin12209Germany
2Ana Trujillo Emparedados y heladosAna TrujilloAvda. de la Constitución 2222México D.F.5021Mexico
3Antonio Moreno TaqueríaAntonio MorenoMataderos 2312México D.F.5023Mexico
4Around the HornThomas Hardy120 Hanover Sq.LondonWA1 1DPUK
5Berglunds snabbköpChristina BerglundBerguvsvägen 8LuleåS-958 22Sweden

SQL Self Join Example

The following SQL statement selects customers from one city (City):

Run SQLSELECT A.CustomerName AS CustomerName1, B.CustomerName AS CustomerName2, A.City 
FROM Customers A, Customers B 
WHERE A.CustomerID <> B.CustomerID 
AND A.City = B.City 
MySQL dialect uses "!=" instead of "<>".