Summary -

In this topic, we described about the Self Join with detailed example.

SELF JOIN the name itself tells that, in SELF JOIN it JOIN the table with itself. SELF JOIN look like it JOIN two copies of same table. Actually it won't copied, SELF JOIN works like that.

Syntax -

SELECT a.column1, a.column2, b.column1,b.column2,…
FROM table a, table b WHERE a.column1 = b.column2;

Example -

consider employee_details table as follows -

employee_details -

emp_id emp_name designation manager_id date_of_hire salary dept_id
001 Employee1 Director 2019-07-11 45000.00 1000
002 Employee2 Director 2019-07-11 40000.00 2000
003 Employee3 Manager Employee1 2019-07-11 27000.00 1000
004 Employee4 Manager Employee2 2019-10-08 25000.00 2000
005 Employee5 Analyst Employee3 2019-07-11 20000.00 1000
006 Employee6 Analyst Employee3 2019-10-08 18000.00 1000
007 Employee7 Clerk Employee3 2019-07-11 15000.00 1000
008 Employee8 Salesman Employee4 2019-09-09 14000.00 2000
009 Employee9 Salesman Employee4 2019-10-08 13000.00 2000

Scenario – Fetching details from table by using SELF JOIN.

Requirement - Fetching details from employee_details table by using SELF JOIN. The query was as follows –

SELECT a.emp_id, b.emp_name, a.salary 
FROM employee_details a, employee_details b 
WHERE a.emp_id <> b.emp_id AND a.salary < b.salary ;

By executing above query we can get output like as follows –

emp_id emp_name salary
002 Employee2 40000.00
003 Employee3 27000.00
004 Employee4 25000.00
005 Employee5 20000.00
006 Employee6 18000.00
007 Employee7 15000.00
008 Employee8 14000.00
009 Employee9 13000.00
003 Employee3 27000.00
004 Employee4 25000.00
005 Employee5 20000.00
006 Employee6 18000.00
007 Employee7 15000.00
008 Employee8 14000.00
009 Employee9 13000.00
004 Employee4 25000.00
005 Employee5 20000.00
006 Employee6 18000.00
007 Employee7 15000.00
008 Employee8 14000.00
009 Employee9 13000.00
005 Employee5 20000.00
006 Employee6 18000.00
007 Employee7 15000.00
008 Employee8 14000.00
009 Employee9 13000.00
006 Employee6 18000.00
007 Employee7 15000.00
008 Employee8 14000.00
009 Employee9 13000.00
007 Employee7 15000.00
008 Employee8 14000.00
009 Employee9 13000.00
008 Employee8 14000.00
009 Employee9 13000.00
009 Employee9 13000.00