SQL Server Self Join
SQL Server Self Join
Summary: in this tutorial, you will learn how to use the SQL Server self join to join a table to itself.
A self join uses the inner join or left join clause. Because the query that uses self join references the
same table, the table alias is used to assign different names to the table within the query.
Note that if you reference the same table more than one in a query without using table aliases, you
will get an error.
To get who reports to whom, you use the self join as shown in the following query:
1 SELECT
2 e.first_name + ' ' + e.last_name employee,
3 m.first_name + ' ' + m.last_name manager
4 FROM
5 sales.staffs e
6 INNER JOIN sales.staffs m ON m.staff_id = e.manager_id
7 ORDER BY
8 manager;
In this example, we referenced to the staffs table twice: one as e for the employees and the other
as m for the managers. The join predicate matches employee and manager relationship using the
values in the e.manager_id and m.staff_id columns.
The employee column does not have Fabiola Jackson because of the INNER JOIN effect. If you
replace the INNER JOIN clause by the LEFT JOIN clause as shown in the following query, you will
get the result set that includes Fabiola Jackson in the employee column:
1 SELECT
2 e.first_name + ' ' + e.last_name employee,
3 m.first_name + ' ' + m.last_name manager
4 FROM
5 sales.staffs e
6 LEFT JOIN sales.staffs m ON m.staff_id = e.manager_id
7 ORDER BY
8 manager;
2) Using self join to compare rows within a table
See the following customers table:
The following statement uses the self join to find the customers located in the same city.
1 SELECT
2 c1.first_name + ' ' + c1.last_name customer_1,
3 c2.first_name + ' ' + c2.last_name customer_2,
4 c1.city
5 FROM
6 sales.customers c1
7 INNER JOIN sales.customers c2 ON c1.customer_id <> c2.customer_id
8 AND c1.city = c2.city
9 ORDER BY
10 customer_1,
11 customer_2;
In this tutorial, you have learned how to use an SQL Server self join to query hierarchical data and
compare rows in the same table.