SELF JOIN Examples - SQL Query
A Self join is used in condition where user needs to create a result set that joins records in a table with other records in the same table.
Consider the following table 'Students'.
Stud_ID | Stud_Name | Stud_Location |
---|
1 | Jaya | INDIA |
2 | Albert | USA |
3 | Andrew | USA |
4 | Robin | UK |
5 | Shruti | INDIA |
Write a query to find out which students are from the same location as Student 'Jaya'.
Answer:
SELECT S2.Stud_Name
FROM Students S1, Students S2
WHERE S1.Stud_location = S2.Stud_location
AND S1.Stud_Name='Jaya';
In the above query S1 and S2 are used as Aliases. So this query will find the Students from same location.
Output: