blog post

A self JOIN occurs when a table takes a 'selfie'.
A self JOIN is a regular join but the table is joined with itself.
This can be useful when modeling hierarchies.
They are also useful for comparisons within a table.

The SQL Self JOIN syntax

The general syntax is:
SELECT column-names
  FROM table-name T1 JOIN table-name T2
  WHERE condition

T1 and T2 are different table aliases for the same table

SQL Self JOIN Examples

Problem: Match customers that are from the same city and country
SELECT B.FirstName AS FirstName1, B.LastName AS LastName1, 
       A.FirstName AS FirstName2, A.LastName AS LastName2, 
       B.City, B.Country
  FROM Customer A, Customer B
 WHERE A.Id <> B.Id
   AND A.City = B.City 
   AND A.Country = B.Country
 ORDER BY A.Country

A and B are aliases for the same Customer table.

  • Share This Story


Pleas give your valuable comments to improve the contents.

about author

Atul kumar shukla


I'm Atul Kumar Shukla, working as a web developer.
Welcome to my Blog. This is my personal blog where i post my own questions and answers , articles about ASP.Net., SQL Server, HTML, CSS, Jquery and many more..

Visit Profile

Leave a comment

Name
E-mail
Url
Message

Get More Stuff
Subscribing to the TheOneblogs newsletter and get intersting stuff and updates to your email inbox.
Your Email

 

Style Switcher

Change Color

×! We use cookies to improve your user experience. More information