Self & Cross Joins
Join a table to itself to follow manager links, and use CROSS JOIN to build every combination of two lists.
Two special joins
A self join joins a table to itself. It is not a new keyword: you list the same table twice with two different aliases, and treat each copy as its own table. It is used when a row points at another row of the same table, such as an employee who points at a manager.
A cross join pairs every row of one table with every row of another. There is no ON, so nothing is filtered. Two tables with 3 and 2 rows give 3 x 2 = 6 rows.
Trees and combinations
Org charts, comment threads and category trees all store a link to a row in the same table. A self join turns that link into a name you can read. A cross join builds every size and color combination for a shop without typing them out.
Show each employee next to their manager
SELECT e.name AS employee, m.name AS manager
FROM staff AS e
LEFT JOIN staff AS m
ON e.manager_id = m.id;e is the employee copy of staff and m is the manager copy. The ON test says: take the employee's manager_id and find the row with that id. Aliases are required here, because without them both copies would have the same name.
Asha has NULL as her manager, so the LEFT JOIN shows her with a NULL manager. An INNER JOIN would drop her.
A cross join is written without ON: FROM sizes CROSS JOIN colors. Sizes S, M, L and colors Red, Blue give 6 pairs. It is the same as an inner join whose test is always true.
Follow the manager link
Switch between INNER and LEFT in the self join and watch Asha appear and disappear. Then switch to the cross join and count the pairs.
| idinteger | nametext | manager_idinteger |
|---|---|---|
| 1 | Asha | NULL |
| 2 | Ben | 1 |
| 3 | Chen | 1 |
| 4 | Dara | 2 |
| 5 | Eli | 2 |
| idinteger | nametext | manager_idinteger |
|---|---|---|
| 1 | Asha | NULL |
| 2 | Ben | 1 |
| 3 | Chen | 1 |
| 4 | Dara | 2 |
| 5 | Eli | 2 |
| employeetext | managertext |
|---|---|
| Asha | NULL |
| Ben | Asha |
| Chen | Asha |
| Dara | Ben |
| Eli | Ben |
LEFT keeps every employee. Asha has no manager, so her manager is NULL. The aliases e and m are required, because both sides are the same table.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- A self join lists the same table twice with two aliases, and needs an ON test that links the two copies.
- Use LEFT JOIN in a self join when the top row has no parent.
- CROSS JOIN has no ON and returns every pairing, so N rows and M rows give N x M rows.
- A cross join is the same as an inner join whose test is always true.
Done with this concept?
Mark it complete to track your progress. No login needed.