- passive income

What is self join in SQL

An SQL join clause - corresponding to a join operation in relational algebra - combines columns from one or more tables in a relational database . We know about inner join , left join , natural join etc in SQL . But most of them don’t know what is self join and how does it work ? Now we are going to know what is self join and how does it work . We can use a self join when a table references data in itself. To clearly understand see the following table .

See , This is our Employee table and we have to find out who works under the manager . Here Sonam is the manager and Rahul and Jay works under  Sonam . Thereafter The manager of Sonam is Kunal . Furthermore The manager of Ram is Rani and Rani does’nt have any manager . That mean you can say She is CEO. Hope you will understand. So let’s learn how to write this query . See the final report of their works under manager. 

Hope you will understand. Let’s see the query

SELECT Name , Manager
       FROM employee e 
       INNER JOIN employee m 
       ON e.managerId = m.employeeId

See we have been joined in one table & we create two aliases . That’s why one copy table created automatically from the base table to compare itself. Hope you will understand it. Just like this below pic. 

Hope you got it. Now the see the output of this query . 

Hope you will understand above discussion . If you like this tutorial please leave a comments and share with your friends. If you find any error of this tutorial , please share this with me. You can read also ADVANCE PHP CRUD APPLICATION WITH PDO

Leave a comments


Recent Tweets