SELF JOIN — Complete Guide
SELF JOIN — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of SQL Server Tutorial on Toolliyo Academy.
On this page
SQL Server Tutorial · Lesson 26 of 100
SELF JOIN
SQL basics → Queries → Advanced
SQL basics · 1 — SELECT · ~6 min · SQL — Joins & Relationships
What is this?
A self join uses the same table twice with different aliases — often for employee→manager or category→parent hierarchies.
Why should you care?
HR needs “who manages Priya?” when ManagerId points at another Employees.EmployeeId.
See it live — copy this example
Run in SQL Server Management Studio (SSMS) or Azure Data Studio.
USE DataVerse;
IF OBJECT_ID(N'dbo.Employees', N'U') IS NOT NULL DROP TABLE dbo.Employees;
CREATE TABLE dbo.Employees (
EmployeeId INT PRIMARY KEY,
FullName NVARCHAR(100) NOT NULL,
ManagerId INT NULL
);
INSERT INTO dbo.Employees VALUES
(1, N'Anita Rao', NULL),
(2, N'Priya Shah', 1),
(3, N'Rohan Das', 1);
SELECT e.FullName AS Employee, m.FullName AS Manager
FROM dbo.Employees AS e
LEFT JOIN dbo.Employees AS m ON m.EmployeeId = e.ManagerId;
What happened?
- Alias e is the employee; alias m is the manager row from the same table.
- LEFT JOIN keeps Anita who has no manager.
Practice next
- Create Employees and run the self join.
- Add another level (Rohan manages someone) and extend the query.
- Find employees whose manager name is Anita.
- Show ManagerId and manager email if you add Email.
- Count direct reports with GROUP BY ManagerId.
Remember
Self join = one table, two roles. Aliases are mandatory for clarity. Common for org charts and bill-of-materials.
Org chart in DataVerse HR
HR app resolves manager names via self join on Employees.
Outcome: Directory page shows Employee — Manager pairs.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!