SQL SELF JOIN
The SELF JOIN
is used to join a table to itself as if it were two tables.
A SELF JOIN
is also called a Unary relationship.
The SELF JOIN
can be viewed as a join of two copies of the same table. The SQL will not copy the table, but it performs as if it does.
Syntax
The syntax for the SELF JOIN
is as follows:
SELECT column_list
FROM tableA A1, tableA A2
WHERE condition;
A1 and A2 are different table aliases for the same table.
Demo Table
Let us suppose that we have a table called "Employee" with the following records:
emp_no | name | birth_date | hire_date | salary | dept_name |
---|---|---|---|---|---|
1001 | James Smith | 1991-10-23 | 2010-05-13 | 6600 | Customer Service |
1002 | Maria Martinez | 1993-06-13 | 2018-10-08 | 9000 | Development |
1003 | Andrew Rodriguez | 1994-10-25 | 2019-01-23 | 9500 | Finance |
1004 | Robert Hernandez | 1995-09-07 | 2019-09-08 | 9600 | Development |
1005 | Donna Williams | 1996-03-15 | 2012-06-06 | 7400 | Finance |
1006 | James Johnson | 2001-04-30 | 2014-02-18 | 8000 | Marketing |
1007 | Stephanie Miller | 1998-01-17 | 2009-12-12 | 8500 | Human Resources |
1008 | Nelson Lopez | 1999-05-26 | 2010-10-06 | 7300 | Marketing |
SQL SELF JOIN Example
The following SQL statement uses the table "Employee" twice to select employees working in the same department.
SELECT A.name AS employee_1, B.name AS employee_2, A.dept_name AS department_name
FROM employee AS A, employee AS B
CROSS A.emp_no <> B.emp_no
AND A.dept_name = B.dept_name
ORDER BY A.dept_name;
After running the above SQL statement, the output will look like the following:
+------------------+------------------+-----------------+ | employee_1 | employee_2 | department_name | +------------------+------------------+-----------------+ | Maria Martinez | Robert Hernandez | Development | | Robert Hernandez | Maria Martinez | Development | | Andrew Rodriguez | Donna Williams | Finance | | Donna Williams | Andrew Rodriguez | Finance | +------------------+------------------+-----------------+