In this tutorial, we will learn how to use SELF JOIN
using SQL.
SELF JOIN
is a join in which a table is joined with itself.SELF JOIN
compares values of the same or different columns in the same table.SELECT column(s)
FROM tableName1 T1,tableName1 T2
WHERE CONDITION;
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 |
This SQL statement matches employee that are from the same city, a query Will be:
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;
EmpName1 | EmpName2 | City |
Shankar | Sourabh | Delhi |
Sourabh | Shankar | Delhi |
Akshay | Ranvijay | Mumbai |
Ranvijay | Akshay | Mumbai |
Rocky | Kapil | Noida |
Kapil | Rocky | Noida |