Joins and set operations
Self joins
Use two aliases of Employees to show each person beside their manager.
Lesson 36 of 84
Reading: about 2 min
Lesson + practice: about 12 min
Difficulty: Intermediate
On this page4 sections
This lesson uses the unmodified DDI_SQL_Training dataset v1.0.0 on SQL Server 2019 or later. Use two aliases of Employees to show each person beside their manager.
Run the example
SELECT TOP (5) e.EmployeeID, e.FirstName AS EmployeeName,
m.FirstName AS ManagerName
FROM dbo.Employees AS e
LEFT JOIN dbo.Employees AS m ON m.EmployeeID = e.ManagerID
ORDER BY e.EmployeeID;Read it step by step
- e and m are separate aliases for the same Employees table.
- e.ManagerID references the employee row represented by m.
- LEFT JOIN retains employees with no manager, showing NULL for ManagerName.
Check the result
| EmployeeID | EmployeeName | ManagerName |
|---|---|---|
| 1 | Amina | NULL |
| 2 | Grace | Amina |
| 3 | Marcus | Amina |
| 4 | Sofia | Amina |
| 5 | Oliver | NULL |
A NULL ManagerName here means no manager row was linked; it is not an empty string.
Practice
Show the first three employees who have a manager, with EmployeeID and their manager’s FirstName.
Check your answer and expected result
Reveal answer
SELECT TOP (3) e.EmployeeID, m.FirstName AS ManagerName
FROM dbo.Employees AS e
JOIN dbo.Employees AS m ON m.EmployeeID = e.ManagerID
ORDER BY e.EmployeeID;| EmployeeID | ManagerName |
|---|---|
| 2 | Amina |
| 3 | Amina |
| 4 | Amina |
The INNER JOIN excludes employees whose ManagerID is NULL.
Your progress
Reveal the check answer or reach the end to complete this lesson.