The aim of this page๐ is to explain self-joins in SQL and how they can be used effectively.
- Definition: A self-join is a regular join but the table is joined with itself.
- Purpose: It is used to compare rows within the same table or to create a hierarchical structure.
-
Example Table: A
healthcare_providers
table with columnsname
,id
, andsupervisor_id
. - Basic SQL Query:
SELECT *
FROM healthcare_providers;
- Data Representation: Example data:
โโโโโโโโโโโณโโโโโณโโโโโโโโโโโโโโโโ
โ name โ id โ supervisor_id โ
โกโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฉ
โ Alice โ 2 โ 1 โ
โ Bob โ 3 โ 1 โ
โ Carol โ 4 โ 5 โ
โ David โ 5 โ NULL โ
โ Eve โ 1 โ 5 โ
โโโโโโโโโโโดโโโโโดโโโโโโโโโโโโโโโโ
- Self-Join Query:
SELECT
e.name AS employee,
s.name AS reports_to
FROM healthcare_providers e
LEFT JOIN healthcare_providers s ON e.supervisor_id = s.id
ORDER BY s.name NULLS LAST;
-
Explanation:
-
Aliases:
e
represents employees,s
represents supervisors. - LEFT JOIN: Ensures all employees are listed, even if they don't have supervisors.
-
ON Clause: Links
supervisor_id
frome
toid
ins
. - SELECT Clause: Retrieves employee names and their respective supervisor names.
- ORDER BY: Sorts the result by supervisor names, keeping null values at the end.
-
Aliases:
- Result:
| employee | reports_to |
|----------|------------|
| Alice | Eve |
| Bob | Eve |
| Carol | David |
| Eve | David |
| David | NULL |
Top comments (0)