MySQL Self Join

MySQL SELF JOIN

A SELF JOIN is a join in which a table is joined with itself.
It is useful when you want to compare rows within the same table or find relationships among rows in the same table.

⚠️ Always use table aliases to distinguish between the two instances of the same table.


 Syntax



 

  • a → Alias for the first instance of the table

  • b → Alias for the second instance of the table


🧠 Example Table: employees

emp_id name manager_id
1 John NULL
2 Emma 1
3 Raj 1
4 Sara 2
5 Aman 2
  • manager_id refers to emp_id of another employee in the same table.


 SQL Query: Find Employee and Their Manager



 


 Result

Employee Manager
John NULL
Emma John
Raj John
Sara Emma
Aman Emma

✅ Notice:

  • John has no manager → Manager = NULL

  • Emma and Raj report to John

  • Sara and Aman report to Emma


 Use Cases of SELF JOIN

  1. Hierarchical data: Employees and managers

  2. Comparisons within the same table: Find rows with similar values

  3. Finding duplicates: Compare a row with other rows in the same table


 Key Points

  1. SELF JOIN is just a regular join with the same table used twice.

  2. Always use aliases to avoid confusion.

  3. Can be used with INNER JOIN, LEFT JOIN, or RIGHT JOIN.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *