SELF JOIN

The SQL Self Join

A self join is a regular join, but the table is joined with itself. You must use two different aliases so SQL can tell the two copies apart.

SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;

-- or, with JOIN syntax
SELECT column_name(s)
FROM table1 AS T1
JOIN table1 AS T2 ON condition;

Example

Example

Customers who are in the same city as another customer:

SELECT A.CustomerName AS Customer1, B.CustomerName AS Customer2, A.City
FROM Customers A
JOIN Customers B
  ON A.City = B.City
 AND A.CustomerID < B.CustomerID;

Result: 1 row

Customer1Customer2City
Blue Harbor FoodsHarbor LightsLondon

A.CustomerID < B.CustomerID stops a customer being paired with itself, and stops each pair appearing twice (A,B and B,A).

Reporting Lines

Employees.ManagerID stores the EmployeeID of each person's manager, a reference to the same table.

Example

Each employee with their manager's name:

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

Result: 6 rows

EmployeeManager
RahulNULL
SaraRahul
DavidRahul
AnanyaJames
JamesNULL
FatimaNULL

A LEFT self join keeps employees with no manager (top of the hierarchy).

Employees Earning More Than Their Manager

Example

A classic interview question:

SELECT e.FirstName, e.Salary, m.FirstName AS Manager, m.Salary AS ManagerSalary
FROM Employees e
JOIN Employees m ON m.EmployeeID = e.ManagerID
WHERE e.Salary > m.Salary;

Result: 0 rows

FirstNameSalaryManagerManagerSalary

No one in the demo data earns more than their manager, so the result is empty. Try raising Sara's salary and run it again.

Count Direct Reports

Example

Number of people reporting directly to each manager:

SELECT m.FirstName AS Manager, COUNT(e.EmployeeID) AS DirectReports
FROM Employees m
JOIN Employees e ON e.ManagerID = m.EmployeeID
GROUP BY m.FirstName;

Result: 2 rows

ManagerDirectReports
James1
Rahul2

Pairs and Ranges

Example

Products in the same category where one is more expensive than the other:

SELECT a.Category, a.ProductName AS Pricier, b.ProductName AS Cheaper,
       ROUND(a.Price - b.Price, 2) AS Difference
FROM Products a
JOIN Products b ON a.Category = b.Category AND a.Price > b.Price;

Result: 3 rows

CategoryPricierCheaperDifference
GroceryBasmati Rice 5kgOlive Oil 1L2.51
BeveragesEspresso Beans 1kgGreen Tea 100 bags11.25
SnacksAlmonds 500gDark Chocolate4.76

Consecutive Rows

Example

Days between each customer's orders, joining each order with that customer's previous one:

SELECT cur.CustomerID, prev.OrderDate AS PreviousOrder, cur.OrderDate AS ThisOrder,
       julianday(cur.OrderDate) - julianday(prev.OrderDate) AS DaysBetween
FROM Orders cur
JOIN Orders prev
  ON prev.CustomerID = cur.CustomerID
 AND prev.OrderDate = (SELECT MAX(OrderDate) FROM Orders x
                       WHERE x.CustomerID = cur.CustomerID AND x.OrderDate < cur.OrderDate);

Result: 2 rows

CustomerIDPreviousOrderThisOrderDaysBetween
12024-01-052024-02-1844
42024-01-122024-03-2270

Tip: The LAG() window function does this more simply (Advance level, Advanced SQL).