loading

SQL Self Join

SQL Self Join

A self join is just a normal join except that it joins the table to 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

We’ll be using the well-known Northwind sample database in this tutorial.

A sample from the “Customers” table is shown below:

CustomerID CustomerName ContactName Address City PostalCode Country
1

Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico

SQL Self Join Example

Customers from the same city are matched using the SQL statement that follows:

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;
				
			
Share this Doc

SQL Self Join

Or copy link

Explore Topic