bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths

Loading lesson path

Learn/SQL/SQL Tutorial
SQL•SQL Tutorial

SQL Self Join

A self join is a regular join, but the table is joined with itself.

Self Join Syntax

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

T1 and T2 are different table aliases for the same table.

Demo Database

Below is a selection from the "Customers" table:

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
1Alfreds FutterkisteMaria AndersObere Str. 57Berlin12209Germany
2Ana Trujillo Emparedados y heladosAna TrujilloAvda. de la Constitución 2222México D.F.05021Mexico
3Antonio Moreno TaqueríaAntonio MorenoMataderos 2312México D.F.05023Mexico

SQL Self Join Example

The following SQL statement matches customers that are from the same city:

Example

  SELECT 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
ORDER BY A.City;

Previous

SQL FULL JOIN

Next

SQL UNION Operator