RSS Feed

SQL Self Join

SQL Self Join

Joining a table to itself is called self join.

Example of Self Join

Suppose you have a table that stores an employee identification number, the employee’s name, and the employee identification number of the employee’s manager. You might want to produce a list of all employees and their managers’ names. The problem is that the manager name does not exist as a category in the table:

SELECT * FROM EMP;

IDNAMEMGR_ID
1JOHN0
2MARY1
3STEVE1
4JACK2
5SUE2

In the following example, we have included the table EMP twice in the FROM clause of the query, giving the table two aliases for the purpose of the query. By providing two aliases, it is as if you are selecting from two distinct tables. All managers are also employees, so the JOIN condition between the two tables compares the value of the employee identification number from the first table with the manager identification number in the second table. The first table acts as a table that stores employee information, whereas the second table acts as a table that stores manager information:

SELECT E1.NAME, E2.NAME
FROM EMP E1, EMP E2
WHERE E1.MGR_ID = E2.ID;

NameName
MARYJOHN
STEVEJOHN
JACKMARY
SUEMARY

[Source: Sams Teach Yourself SQL in 24 Hours By Ryan Stephens, Ron Plew, Arie Jones]

Why use self join

While self-joins rarely are used on a normalized database, you can use them to reduce the number of queries that you execute when you compare values of different columns of the same table.

When you use self-joins, consider the following guidelines:

You must specify table aliases to reference two copies of the table. Remember that table aliases are different from column aliases. Table aliases are designated as the table name followed by the alias.

When you create self-joins, each row matches itself and pairs are repeated, resulting in duplicate rows. Use a WHERE clause to eliminate these duplicate rows [Microsoft SQL Server 7.0 data warehousing training]

[Source: Microsoft SQL Server 7.0 data warehousing training]