ELEVATE YOUR BUSINESS WITH

Limitless customization options & Elementor compatibility let anyone create a beautiful website with Valiance.

Self Join in MySql

SELECT * FROM `itio_tutorial_master` WHERE `tutorial_menu`='7' AND `tutorial_submenu`='54' AND `tutorial_status`=1 LIMIT 1

Self Join in MySql

SELF JOIN in MySQL

A SELF JOIN is a type of JOIN where a table is joined with itself. It is used when rows in a table need to be compared with other rows in the same table.


1. Syntax

SELECT A.column1, B.column2FROM table_name AJOIN table_name B ON A.common_column = B.common_column;

  • The same table is used twice, with different aliases (A and B).
  • It allows comparing records within the same table.

2. Example Table: employees

emp_idnamemanager_id
1AliceNULL
2Bob1
3Charlie1
4David2

🔹 Each employee has a manager_id that refers to another emp_id in the same table.


3. Using SELF JOIN to Find Employee-Manager Relationships

SELECT A.name AS Employee, B.name AS ManagerFROM employees AJOIN employees B ON A.manager_id = B.emp_id;

✅ Result:

EmployeeManager
BobAlice
CharlieAlice
DavidBob

Explanation

  • The employees table is used twice:
    • A represents employees.
    • B represents their managers.
  • The JOIN is done using A.manager_id = B.emp_id, linking each employee to their manager.

4. Finding Employees Without a Manager (LEFT JOIN)

SELECT A.name AS Employee, COALESCE(B.name, 'No Manager') AS ManagerFROM employees ALEFT JOIN employees B ON A.manager_id = B.emp_id;

✅ Result:

EmployeeManager
AliceNo Manager
BobAlice
CharlieAlice
DavidBob

🔹 COALESCE(B.name, 'No Manager') replaces NULL with "No Manager".


Key Takeaways

✅ SELF JOIN is used to compare records within the same table.
✅ It is useful for hierarchical data (e.g., employees & managers).
✅ Aliases (A, B) are used to differentiate between the two instances of the same table.
✅ LEFT JOIN helps find records with no match (e.g., employees without managers).

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql