Purpose of SELF JOIN


⭐ What Is a Self Join (in Simple Words)?

A self join means joining the same table with itself to compare one row with another row in the same table.

To avoid confusion, we give the table two names (aliases).

Let’s learn with very easy examples 👇


Example 1: Employees and Their Managers (Simple Hierarchy)

Table: employees

idnamemanager_id
1Karthik3
2Priya3
3RameshNULL

Here:

  • Ramesh is the manager of Karthik and Priya.

✔ Self Join Query:

SELECT e.name AS employee,
       m.name AS manager
FROM employees e
LEFT JOIN employees m
      ON e.manager_id = m.id;

✔ Output:

employeemanager
KarthikRamesh
PriyaRamesh
RameshNULL

Why self join?
Because employees and managers are in the same table.


Example 2: Finding People Who Live in the Same City

Table: persons

idnamecity
1ArunChennai
2BalaChennai
3DeviBangalore
4ManiChennai

We want to find pairs of people who are from the same city.

✔ Self Join Query:

SELECT p1.name AS person1,
       p2.name AS person2,
       p1.city
FROM persons p1
JOIN persons p2
     ON p1.city = p2.city
    AND p1.id < p2.id;

✔ Output:

person1person2city
ArunBalaChennai
ArunManiChennai
BalaManiChennai

Why self join?
Because we compare two people in the same table.


Example 3: Finding Duplicate Phone Numbers

Table: customers

idnamephone
1Alex9991110001
2Balu9991110001
3Ram8882220033

We want to find customers who share the same phone number.

✔ Self Join Query:

SELECT c1.name AS customer1,
       c2.name AS customer2,
       c1.phone
FROM customers c1
JOIN customers c2
     ON c1.phone = c2.phone
    AND c1.id < c2.id;

✔ Output:

customer1customer2phone
AlexBalu9991110001

Why self join?
To compare one customer’s phone number to other customers’ phone numbers.


Example 4: Show Products With Higher Price Than Another Product

Table: products

idproductprice
1Pen10
2Pencil5
3Marker20

We want to find all products that are more expensive than another product.

✔ Self Join Query:

SELECT p1.product AS expensive_product,
       p2.product AS cheaper_product
FROM products p1
JOIN products p2
     ON p1.price > p2.price;

✔ Output:

expensive_productcheaper_product
PenPencil
MarkerPen
MarkerPencil

Why self join?
Because we compare prices of rows in the same table.


🎯 Summary (In the Easiest Form)

A self join is used when:

SituationWhy Self Join?
Employee–managerBoth stored in same table
Same city peopleCompare rows in same table
Duplicate checkingCompare same table with itself
Compare values (price, age, weight)Compare one row to another

Comments