Table of Contents

Introduction

SQL Server Self Join Clause is a technique used to join a table with itself. It allows you to retrieve related records from the same table by comparing rows using a common column or a related value.

Unlike INNER JOIN, LEFT JOIN, or RIGHT JOIN, SELF JOIN is not a separate SQL Server JOIN type. It is a regular join operation in which the same table is referenced more than once using different table aliases.

SELF JOIN is useful when a table contains hierarchical or relational data, such as employees and managers, categories and parent categories, or products and related products.

SQL Server SELF JOIN Syntax

The following is the basic syntax of a SELF JOIN in SQL Server:

SELECT
    A.column_name,
    B.column_name
FROM table_name AS A
JOIN table_name AS B
ON A.common_column = B.common_column;

Syntax explanation:

  • SELECT: Specifies the columns to retrieve.
  • FROM: Specifies the table used in the query.
  • table_name AS A: Creates the first alias for the table.
  • JOIN table_name AS B: References the same table again with another alias.
  • ON: Defines the relationship between the two references.
  • A and B: Represent two different references to the same table.

The table aliases are important because they help SQL Server distinguish between the two references to the same table.

SQL Server SELF JOIN Example

Let’s understand how SELF JOIN works with a practical example.

Suppose we have an Employees table that contains employee information and the ID of each employee’s manager.

Employees Table

EmployeeID EmployeeName ManagerID
1 John NULL
2 David 1
3 Sarah 1
4 Michael 2
5 Robert 2
6 Emma 3

In this table, the ManagerID column stores the EmployeeID of the employee’s manager.

For example:

  • John has no manager because ManagerID is NULL.
  • David and Sarah report to John.
  • Michael and Robert report to David.
  • Emma reports to Sarah.

Now, let’s retrieve employee names along with their manager names using SELF JOIN.

SELECT
    e.EmployeeName AS Employee,
    m.EmployeeName AS Manager
FROM Employees AS e
INNER JOIN Employees AS m
ON e.ManagerID = m.EmployeeID;

Output:

Employee Manager
David John
Sarah John
Michael David
Robert David
Emma Sarah

Explanation:

  • e represents the employee record.
  • m represents the manager record.
  • Both aliases refer to the same Employees table.
  • The ON condition matches each employee’s ManagerID with the manager’s EmployeeID.
  • John does not appear as an employee in the output because his ManagerID is NULL.

This example demonstrates how SELF JOIN retrieves related records from the same table.

SQL Server SELF JOIN with INNER JOIN

You can use INNER JOIN to retrieve only records that have a matching relationship within the same table.

For example, the following query retrieves employees who have an assigned manager.

SELECT
    e.EmployeeID,
    e.EmployeeName,
    m.EmployeeName AS ManagerName
FROM Employees AS e
INNER JOIN Employees AS m
ON e.ManagerID = m.EmployeeID;

Explanation:

INNER JOIN returns only employees whose ManagerID matches another employee’s EmployeeID.

Employees without a manager are excluded because their ManagerID does not match another employee record.

SQL Server SELF JOIN with LEFT JOIN

You can use LEFT JOIN with SELF JOIN to retrieve all employees, including employees who do not have a manager.

SELECT
    e.EmployeeID,
    e.EmployeeName,
    m.EmployeeName AS ManagerName
FROM Employees AS e
LEFT JOIN Employees AS m
ON e.ManagerID = m.EmployeeID;

Output:

EmployeeID EmployeeName ManagerName
1 John NULL
2 David John
3 Sarah John
4 Michael David
5 Robert David
6 Emma Sarah

Explanation:

  • The left side represents all employee records.
  • The right side represents the corresponding manager records.
  • LEFT JOIN preserves every employee.
  • John appears with NULL as ManagerName because he has no manager.

This approach is useful when you need to display complete employee information, including top-level employees.

SQL Server SELF JOIN with WHERE Clause

You can use the WHERE clause with SELF JOIN to filter records based on specific conditions.

For example, the following query retrieves employees who report directly to John.

SELECT
    e.EmployeeName AS Employee,
    m.EmployeeName AS Manager
FROM Employees AS e
INNER JOIN Employees AS m
ON e.ManagerID = m.EmployeeID
WHERE m.EmployeeName = 'John';

Output:

Employee Manager
David John
Sarah John

The WHERE clause filters the joined result and returns only employees whose manager is John.

SQL Server SELF JOIN with Comparison Operators

SELF JOIN can also be used with comparison operators to compare records in the same table.

Suppose we have a Products table containing product information.

Products Table

ProductID ProductName Price
1 Keyboard 800
2 Mouse 500
3 Monitor 12000
4 Headphone 1500

The following query retrieves pairs of products where the first product has a higher price than the second product.

SELECT
    p1.ProductName AS Product1,
    p1.Price AS Price1,
    p2.ProductName AS Product2,
    p2.Price AS Price2
FROM Products AS p1
INNER JOIN Products AS p2
ON p1.Price > p2.Price;

Explanation:

  • p1 represents the first product reference.
  • p2 represents the second product reference.
  • The ON condition compares the prices of two product records.
  • The query returns product pairs where the first product is more expensive.

This technique can be useful for comparing records within the same table.

SQL Server SELF JOIN to Find Duplicate Records

SELF JOIN can be used to identify records with matching values in a table.

For example, suppose an Employees table contains employee email addresses. The following query identifies employees who share the same email address.

SELECT
    e1.EmployeeID,
    e1.EmployeeName,
    e2.EmployeeID AS DuplicateEmployeeID,
    e2.EmployeeName AS DuplicateEmployeeName,
    e1.Email
FROM Employees AS e1
INNER JOIN Employees AS e2
ON e1.Email = e2.Email
AND e1.EmployeeID < e2.EmployeeID;

Explanation:

  • The query compares email addresses from two references to the Employees table.
  • e1.Email = e2.Email identifies matching email addresses.
  • e1.EmployeeID < e2.EmployeeID prevents a row from matching itself and avoids displaying each pair twice.

This query assumes EmployeeID uniquely identifies each employee. It can help identify duplicate values before applying data-cleaning rules.

SQL Server SELF JOIN with ORDER BY

The ORDER BY clause can be used with SELF JOIN to sort the returned records.

SELECT
    e.EmployeeName AS Employee,
    m.EmployeeName AS Manager
FROM Employees AS e
LEFT JOIN Employees AS m
ON e.ManagerID = m.EmployeeID
ORDER BY e.EmployeeName ASC;

This query returns all employees and their managers, sorted alphabetically by employee name.

You can also sort the records by manager name:

SELECT
    e.EmployeeName AS Employee,
    m.EmployeeName AS Manager
FROM Employees AS e
LEFT JOIN Employees AS m
ON e.ManagerID = m.EmployeeID
ORDER BY m.EmployeeName DESC;

SQL Server SELF JOIN with Multiple Conditions

You can use multiple conditions in the ON clause when joining a table with itself.

For example, suppose a Products table contains ProductID, ProductName, CategoryID, and Price.

The following query finds products in the same category that have different product IDs.

SELECT
    p1.ProductName AS Product1,
    p2.ProductName AS Product2,
    p1.CategoryID
FROM Products AS p1
INNER JOIN Products AS p2
ON p1.CategoryID = p2.CategoryID
AND p1.ProductID < p2.ProductID;

Explanation:

  • The first condition matches products with the same CategoryID.
  • The second condition prevents a product from being compared with itself.
  • The query returns each product pair only once.

This example is useful when comparing products, services, or other records grouped by a common category.

SQL Server SELF JOIN with Aggregate Functions

Aggregate functions can also be used with SELF JOIN to calculate information about related records.

For example, the following query counts how many employees report to each manager.

SELECT
    m.EmployeeID AS ManagerID,
    m.EmployeeName AS ManagerName,
    COUNT(e.EmployeeID) AS TotalEmployees
FROM Employees AS m
LEFT JOIN Employees AS e
ON m.EmployeeID = e.ManagerID
GROUP BY
    m.EmployeeID,
    m.EmployeeName;

Output:

ManagerID ManagerName TotalEmployees
1 John 2
2 David 2
3 Sarah 1
4 Michael 0
5 Robert 0
6 Emma 0

Explanation:

  • m represents the manager reference.
  • e represents the employee reference.
  • LEFT JOIN preserves every employee record in the manager reference.
  • COUNT calculates how many employees report to each manager.
  • Managers without direct reports receive a count of zero.

SQL Server SELF JOIN for Hierarchical Data

SELF JOIN is commonly used to represent hierarchical relationships in a relational database.

For example, an organization may store employee and manager information in the same Employees table.

The following query displays each employee and their direct manager:

SELECT
    e.EmployeeName AS Employee,
    m.EmployeeName AS Manager
FROM Employees AS e
LEFT JOIN Employees AS m
ON e.ManagerID = m.EmployeeID;

This structure is known as an adjacency-list model. Each record stores a reference to another record in the same table.

SELF JOIN can retrieve one level of the hierarchy. For multiple levels, such as manager, department head, and director, you can use multiple SELF JOIN operations or a recursive Common Table Expression (CTE).

SQL Server SELF JOIN with Multiple Levels

You can use multiple aliases of the same table to retrieve several levels of a hierarchy.

For example, the following query retrieves an employee, their manager, and the manager’s manager.

SELECT
    e.EmployeeName AS Employee,
    m.EmployeeName AS Manager,
    gm.EmployeeName AS GrandManager
FROM Employees AS e
LEFT JOIN Employees AS m
ON e.ManagerID = m.EmployeeID
LEFT JOIN Employees AS gm
ON m.ManagerID = gm.EmployeeID;

Explanation:

  • e represents the employee.
  • m represents the employee’s direct manager.
  • gm represents the manager’s manager.
  • Each alias references the same Employees table.
  • LEFT JOIN keeps employee records even when one or more management levels are missing.

This approach is suitable when the hierarchy has a known and limited number of levels.

Practical SQL Server SELF JOIN Query

The following complete example creates an Employees table, inserts sample records, and retrieves employees with their manager names.

CREATE TABLE Employees
(
    EmployeeID INT PRIMARY KEY,
    EmployeeName VARCHAR(50),
    ManagerID INT NULL
);

INSERT INTO Employees
(
    EmployeeID,
    EmployeeName,
    ManagerID
)
VALUES
(1, 'John', NULL),
(2, 'David', 1),
(3, 'Sarah', 1),
(4, 'Michael', 2),
(5, 'Robert', 2),
(6, 'Emma', 3);

SELECT
    e.EmployeeID,
    e.EmployeeName AS Employee,
    m.EmployeeName AS Manager
FROM Employees AS e
LEFT JOIN Employees AS m
ON e.ManagerID = m.EmployeeID
ORDER BY e.EmployeeID;

Expected result:

EmployeeID Employee Manager
1 John NULL
2 David John
3 Sarah John
4 Michael David
5 Robert David
6 Emma Sarah

The query uses two aliases, e and m, to reference the same Employees table. The LEFT JOIN ensures that all employees appear in the result, including John, who does not have a manager.

This practical example demonstrates how SQL Server SELF JOIN can retrieve hierarchical relationships from a single database table.