;

SQL SELF JOIN


In this tutorial, we will learn how to use SELF JOIN using SQL.

SQL SELF JOIN

  • SQL SELF JOIN is a join in which a table is joined with itself.
  • You can not refer the same table more than one in a query, So table alias is used to assign different names to the table within a query.
  • SQL SELF JOIN compares values of the same or different columns in the same table.
Syntax - SELF JOIN
SELECT column(s)
FROM tableName1 T1,tableName1 T2
WHERE CONDITION;

Example:

Let us consider this table "Employee" for records.

Table Name: Employee

ID EmpName City Country Gender Salary
1 Shankar Delhi India male 25000
2 Sourabh Delhi India male 30000
3 Ranvijay Mumbai India male 15000
4 Kapil Noida India male 25000
5 Shalini Jaipur India female 18000
6 Rakesh Faridabad India male 23000
7 Akshay Mumbai India male 21000
8 Sarah New York US female 76000
9 Rocky Noida India male 28000

Example of SELF JOIN

This SQL statement matches employee that are from the same city, a query Will be:

Example 
SELECT A.EmpName AS EmpName1, B.EmpName AS EmpName2, A.City
FROM Employee A, Employee B
WHERE A.ID <> B.ID
AND A.City = B.City 
ORDER BY A.City;
Output
EmpName1 EmpName2 City
Shankar Sourabh Delhi
Sourabh Shankar Delhi
Akshay Ranvijay Mumbai
Ranvijay Akshay Mumbai
Rocky Kapil Noida
Kapil Rocky Noida