Hi friend
I want to know what is self join in in sql server?
Thank you.
Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Satyapriya NayakRank #47 · 31.5K reputationPosted May 7, 2012, 6:02 PM EDT
When all of the data you want to retrieve is contained within a single table, but data needed to extract is related to each other in the table itself.
In our example, 3 columns emp_id, emp_name and emp_mgr. Now
For example: Table named Emp_details containing information of all employees, Now you want to know the manager for every employee.
Follow as below, to create and insert the data to proceed for the self join example.
create table Emp_details
(
emp_id int,
emp_name varchar(25),
mgr_no int
)
insert into Emp_details
select 1, 'Jeff', 4
union all
select 2, 'Mark', 4
union all
select 3, 'Ben', 4
union all
select 4, 'Kenny', NULL
After insertion, You will see Kenny's emp_id is 4 and her mgr_no is NULL which is 4 for others.
Self join can be an inner or outer join, lets make a self join to retrieve details of employees with their respective manager.
select t1.emp_id, t1.emp_name, t2.emp_name from Emp_details as t1 inner join Emp_details as t2 on t1.mgr_no = t2.emp_id
Please refer the below link
http://hightechpost.blogspot.in/2011/07/self-join-in-sql-server.html
http://learnsqlserver.in/3/Self-Join.aspx
Thanks
SenthilkumarRank #387 · 6.5K reputationPosted May 7, 2012, 7:02 PM EDT
I suggest you to go through this pinal dave article for good understanding with suitable example.
http://blog.sqlauthority.com/2010/07/08/sql-server-the-self-join-inner-join-and-outer-join/
Jignesh TrivediRank #16 · 50.3K reputationPosted May 7, 2012, 7:25 PM EDT
A Self Join is a type of sql join which is used to join a table to itself, particularly when the table has a FOREIGN KEY that references its own PRIMARY KEY. It is necessary to ensure that the join statement defines an alias for both copies of the table to avoid column ambiguity.
Example
SELECT a.*,b.*
FROM Table1 a, Table1 b
WHERE a.pk = b.pk1;
Please refer
http://blog.sqlauthority.com/2010/07/08/sql-server-the-self-join-inner-join-and-outer-join/
hope this help.