Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 2

A table can be joined to itself in a self-join.

For example, you can use a self-join to find


the products that are supplied by more than one vendor.

Because this query involves a join of the ProductVendor table with itself, the
ProductVendor table appears in two roles. To distinguish these roles, you must give the
ProductVendor table two different aliases (pv1 and pv2) in the FROM clause. These
aliases are used to qualify the column names in the rest of the query. This is an example
of the self-join Transact-SQL statement:

Copy
USE AdventureWorks;
GO
SELECT DISTINCT pv1.ProductID, pv1.VendorID
FROM Purchasing.ProductVendor pv1
INNER JOIN Purchasing.ProductVendor pv2
ON pv1.ProductID = pv2.ProductID
AND pv1.VendorID <> pv2.VendorID
ORDER BY pv1.ProductID

For self join in sql you can try the following example:

Create table employees:

emp_id emp_name emp_manager_id


1 John Null
2 Tom 1
3 Smith 1
4 Albert 2
5 David 2
6 Murphy 5
7 Petra 5

Now to get the names of managers from the above single table you can use sub queries or
simply the self join.

Self Join SQL Query to get the names of manager and employees:
select e1.emp_name 'manager',e2.emp_name 'employee'
from employees e1 join employees e2
on e1.emp_id=e2.emp_manager_id

Result:

manager employee
John Tom
John Smith
Tom Albert
Tom David
David Murphy
David Petra

Understanding the Self Join Example

In the above self join query, employees table is joined with itself using table aliases e1
and e2. This creates the two views of a single table.

You might also like