You are on page 1of 12

Self-Join

Self-Joins
• Table is joined to itself
• Table has two roles in the FROM clause
• Tables is assigned two aliases
– Table alias is used to identify which table role is meant
when specifying a column name in any of the other
clauses
• Requires the use of a column qualifier

2
Self-Joins
• List employees and their managers

3
Self-Joins
• manager_id in worker table is equal to employee_id
in manager table

4
SELF-JOIN

5
EMPLOYEES Table
EMPLOYEE_ID|FIRST_NAME|LAST_NAME|MANAGER_ID|
-----------|----------|---------|----------|
101|Lauren |Alexander| NULL|
102|Lisa |James | NULL|
103|Dave |Bernard | NULL|
104|Steve |Carr | 101|
105|Marg |Horner | 103|
106|Scott |Long | 102|
107|Jim |Best | 101|
108|Sue |McDonald | 105|
109|Trish |Albert | 105|
110|Terry |Maxwell | 103|
111|Dave |Nisbet | 104|
112|Anne |Richie | 102|

6
7
Self-Joins
• List all employees, EMPLOYEE_ID|FIRST_NAME|LAST_NAME|MANAGER_ID|
-----------|----------|---------|----------|
including those that do 101|Lauren |Alexander| NULL|
102|Lisa |James | NULL|
not have a manager 103|Dave |Bernard | NULL|
104|Steve |Carr | 101|
105|Marg |Horner | 103|
106|Scott |Long | 102|
107|Jim |Best | 101|
108|Sue |McDonald | 105|
109|Trish |Albert | 105|
110|Terry |Maxwell | 103|
111|Dave |Nisbet | 104|
112|Anne |Richie | 102|

8
9
Self-Join – Manager Example
• List managers and the employees that report to each
manager

10
SELF-JOIN – Manager example

11
12

You might also like