SQL Server Self-Join


A self-join is a join between multiple instances of the same table. With self-joins it is mandatory to alias the instances of the tables differently.

Whenever you have a parent-child relationship within a table you have an opportunity to use a self-join. For example, suppose you had a table of employees. In that table there is a column that contains that employee’s manager id.

Let’s have a look at a few columns of the Employees table used in Itzik Ben-Gan’s book in his book T-SQL Querying published by Microsoft Press in 2015.

Here is our query.

1select E.firstname + ' ' + E.lastname as emp, M.firstname + ' ' + M.lastname as mgr
2from HR.Employees as E
3left outer join HR.Employees as M
4on E.mgrid = M.empid

Here are the results.

In a non-production server, you could use the code below to create the original table at the top of this post. I changed some of the names, however.

1/****** Object:  Table [dbo].[OrgChart]    Script Date: 1/8/2023 12:30:38 PM ******/
2SET ANSI_NULLS ON
3GO
4SET QUOTED_IDENTIFIER ON
5GO
6CREATE TABLE [dbo].[OrgChart](
7    [empid] [int] IDENTITY(1,1) NOT NULL,
8    [firstname] [nvarchar](10) NOT NULL,
9    [title] [nvarchar](30) NOT NULL,
10    [mgrid] [int] NULL
11) ON [PRIMARY]
12GO
13SET IDENTITY_INSERT [dbo].[OrgChart] ON
14 
15INSERT [dbo].[OrgChart] ([empid], [firstname], [title], [mgrid]) VALUES (1, N'Sally', N'CEO', NULL)
16INSERT [dbo].[OrgChart] ([empid], [firstname], [title], [mgrid]) VALUES (2, N'Donald', N'Vice President, Sales', 1)
17INSERT [dbo].[OrgChart] ([empid], [firstname], [title], [mgrid]) VALUES (3, N'Jasmine', N'Sales Manager', 2)
18INSERT [dbo].[OrgChart] ([empid], [firstname], [title], [mgrid]) VALUES (4, N'Bart', N'Sales Representative', 3)
19INSERT [dbo].[OrgChart] ([empid], [firstname], [title], [mgrid]) VALUES (5, N'Hans', N'Sales Manager', 2)
20INSERT [dbo].[OrgChart] ([empid], [firstname], [title], [mgrid]) VALUES (6, N'Peter', N'Sales Representative', 5)
21INSERT [dbo].[OrgChart] ([empid], [firstname], [title], [mgrid]) VALUES (7, N'Ramone', N'Sales Representative', 5)
22INSERT [dbo].[OrgChart] ([empid], [firstname], [title], [mgrid]) VALUES (8, N'Marcy', N'Sales Representative', 3)
23INSERT [dbo].[OrgChart] ([empid], [firstname], [title], [mgrid]) VALUES (9, N'Pat', N'Sales Representative', 5)
24SET IDENTITY_INSERT [dbo].[OrgChart] OFF
25GO