Get to know the data
JOIN revisited
LEFT JOIN
RIGHT JOIN
FULL JOIN
OUTER JOINS
Aliases for tables
18. Aliases in self-joins

Instruction

That's right! Aliases are also convenient in other cases. Let's analyze the following situation:

We want to put information about children and their mothers into a database. At some point, we would also like to show children together with their mothers using a join.

Let's say we store both children and mothers in the same table Person, which has a column named MotherID. This column contains the ID of a mother; this ID is taken from the very same table person.

The question is: can we join the table Person with itself? The answer is simple: yes, we can! You can't write

Person JOIN Person

in your SQL query, but you can provide two different aliases for the same table:

SELECT
  *
FROM Person AS P1
INNER JOIN Person AS P2
  ON P1.ID = P2.MotherID;

Thanks to the aliases, the database engine will use the same table twice—the first time to look for children, and the second time to look for their mothers.

Exercise

We want to know who lives with the student Jack Pearson in the same room. Use a self join to show all information for Jack Pearson together with all information for each student living with him in the same room.

Stuck? Here's a hint!

Type:

SELECT
  *
FROM Student AS S1
INNER JOIN Student AS S2
  ON S1.RoomID = S2.RoomID
WHERE S1.Name = N'Jack Pearson'