Explanation of self-joins

SqlSelf Join

Sql Problem Overview


I don't understand the need for self-joins. Can someone please explain them to me?

A simple example would be very helpful.

Sql Solutions


Solution 1 - Sql

You can view self-join as two identical tables. But in normalization, you cannot create two copies of the table so you just simulate having two tables with self-join.

Suppose you have two tables:

###Table emp1

Id Name Boss_id            
1   ABC   3                   
2   DEF   1                   
3   XYZ   2                   

###Table emp2

Id Name Boss_id            
1   ABC   3                   
2   DEF   1                   
3   XYZ   2                   

Now, if you want to get the name of each employee with his or her boss' names:

select c1.Name , c2.Name As Boss
from emp1 c1
    inner join emp2 c2 on c1.Boss_id = c2.Id

Which will output the following table:

Name  Boss
ABC   XYZ
DEF   ABC
XYZ   DEF

Solution 2 - Sql

It's quite common when you have a table that references itself. Example: an employee table where every employee can have a manager, and you want to list all employees and the name of their manager.

SELECT e.name, m.name
FROM employees e LEFT OUTER JOIN employees m
ON e.manager = m.id

Solution 3 - Sql

A self join is a join of a table with itself.

A common use case is when the table stores entities (records) which have a hierarchical relationship between them. For example a table containing person information (Name, DOB, Address...) and including a column where the ID of the Father (and/or of the mother) is included. Then with a small query like

SELECT Child.ID, Child.Name, Child.PhoneNumber, Father.Name, Father.PhoneNumber
FROM myTableOfPersons As Child
LEFT OUTER JOIN  myTableOfPersons As Father ON Child.FatherId = Father.ID
WHERE Child.City = 'Chicago'  -- Or some other condition or none

we can get info about both child and father (and mother, with a second self join etc. and even grand parents etc...) in the same query.

Solution 4 - Sql

Let's say you have a table users, set up like so:

  • user ID
  • user name
  • user's manager's ID

In this situation, if you wanted to pull out both the user's information and the manager's information in one query, you might do this:

SELECT users.user_id, users.user_name, managers.user_id AS manager_id, managers.user_name AS manager_name INNER JOIN users AS manager ON users.manager_id=manager.user_id

Solution 5 - Sql

Imagine a table called Employee as described below. All employees have a manager which is also an employee (maybe except for the CEO, whose manager_id would be null)

Table (Employee): 

int id,
varchar name,
int manager_id

You could then use the following select to find all employees and their managers:

select e1.name, e2.name as ManagerName
from Employee e1, Employee e2 where
where e1.manager_id = e2.id

Solution 6 - Sql

They are useful if your table is self-referential. For example, for a table of pages, each page may have a next and previous link. These would be the IDs of other pages in the same table. If at some point you want to get a triple of successive pages, you'd do two self-joins on the next and previous columns with the same table's id column.

Solution 7 - Sql

Without the ability for a table to reference itself, we'd have to create as many tables for hierarchy levels as the number of layers in the hierarchy. But since that functionality is available, you join the table to itself and sql treats it as two separate tables, so everything is stored nicely in one place.

Solution 8 - Sql

Apart from the answers mentioned above (which are very well explained), I would like to add one example so that the use of Self Join can be easily shown. Suppose you have a table named CUSTOMERS which has the following attributes: CustomerID, CustomerName, ContactName, City, Country. Now you want to list all those who are from the "same city" . You will have to think of a replica of this table so that we can join them on the basis of CITY. The query below will clearly show what it means:

SELECT A.CustomerName AS CustomerName1, B.CustomerName AS CustomerName2, 
A.City
FROM Customers A, Customers B
WHERE A.CustomerID <> B.CustomerID
AND A.City = B.City 
ORDER BY A.City;

Solution 9 - Sql

There are many correct answers here, but there is a variation that is equally correct. You can place your join conditions in the join statement instead of the WHERE clause.

SELECT e1.emp_id AS 'Emp_ID'
  , e1.emp_name AS 'Emp_Name'
  , e2.emp_id AS 'Manager_ID'
  , e2.emp_name AS 'Manager_Name'
FROM Employee e1 RIGHT JOIN Employee e2 ON e1.emp_id = e2.emp_id

Keep in mind sometimes you want e1.manager_id > e2.id

The advantage to knowing both scenarios is sometimes you have a ton of WHERE or JOIN conditions and you want to place your self join conditions in the other clause to keep your code readable.

No one addressed what happens when an Employee does not have a manager. Huh? They are not included in the result set. What if you want to include employees that do not have managers but you don't want incorrect combinations returned?

Try this puppy;

SELECT e1.emp_id AS 'Emp_ID'
   , e1.emp_name AS 'Emp_Name'
   , e2.emp_id AS 'Manager_ID'
   , e2.emp_name AS 'Manager_Name'
FROM Employee e1 LEFT JOIN Employee e2 
   ON e1.emp_id = e2.emp_id
   AND e1.emp_name = e2.emp_name
   AND e1.every_other_matching_column = e2.every_other_matching_column

Solution 10 - Sql

Self-join is useful when you have to evaluate the data of the table with itself. Which means it'll correlate the rows from the same table.

Syntax: SELECT * FROM TABLE t1, TABLE t2 WHERE t1.columnName = t2.columnName

For example, we want to find the names of the employees whose Initial Designation equals to current designation. We can solve this using self join in following way.

SELECT NAME FROM Employee e1, Employee e2 WHERE e1.intialDesignationId = e2.currentDesignationId

Solution 11 - Sql

One use case is checking for duplicate records in a database.

SELECT A.Id FROM My_Bookings A, My_Bookings B
WHERE A.Name = B.Name
AND A.Date = B.Date
AND A.Id != B.Id

Solution 12 - Sql

It's the database equivalent of a linked list/tree, where a row contains a reference in some capacity to another row.

Solution 13 - Sql

Here is the exaplanation of self join in layman terms. Self join is not a different type of join. If you have understood other types of joins (Inner, Outer, and Cross Joins), then self join should be straight forward. In INNER, OUTER and CROSS JOINS, you join 2 or more different tables. However, in self join you join the same table with itslef. Here, we don't have 2 different tables, but treat the same table as a different table using table aliases. If this is still not clear, I would recomend to watch the following youtube videos.

Self Join with an example

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlex GordonView Question on Stackoverflow
Solution 1 - SqlpointlesspoliticsView Answer on Stackoverflow
Solution 2 - SqlwindyjonasView Answer on Stackoverflow
Solution 3 - SqlmjvView Answer on Stackoverflow
Solution 4 - SqlceejayozView Answer on Stackoverflow
Solution 5 - SqlKlaus Byskov PedersenView Answer on Stackoverflow
Solution 6 - SqlMax ShawabkehView Answer on Stackoverflow
Solution 7 - SqlEugeneView Answer on Stackoverflow
Solution 8 - SqlMazhar MIKView Answer on Stackoverflow
Solution 9 - SqlBClaydonView Answer on Stackoverflow
Solution 10 - SqlSumanth VaradaView Answer on Stackoverflow
Solution 11 - SqlMolossus SpondeeView Answer on Stackoverflow
Solution 12 - SqlUnslicedView Answer on Stackoverflow
Solution 13 - Sqluser1472512View Answer on Stackoverflow