lesson 22 Joins & sets · intermediate
Self-joins & referral relationships
Join a table to itself to explore relationships.
the idea
A self-join uses the same table in two roles. Use different aliases for the member and referrer. LEFT JOIN retains members who were not referred.
tables in this lesson
The challenges use this data. Each column shows its type underneath; → marks a link to another table.
members5 columns · 8 rows
| idinteger · key | emailtext | countrytext | joined_attext | referrer_idinteger |
|---|---|---|---|---|
| 1 | ALICE@Example.com | US | 2025-01-01 | NULL |
| 2 | ben@example.com | US | 2025-01-02 | 1 |
| 3 | Cara@example.com | GB | 2025-01-03 | 1 |
| 4 | dev@example.com | IN | 2025-01-04 | 2 |
| 5 | NULL | CA | 2025-01-05 | NULL |
showing 5 of 8 rows
example
The idea in one query. Press Run to see what it returns; running examples never affects your progress.
SELECT m.id AS member_id,r.id AS referrer_id FROM members m LEFT JOIN members r ON r.id=m.referrer_id;
Watch for: The member’s country and the referrer’s country are different attributes.
build it step by step
Each step changes one thing. Run them in order and watch the result change.
Read members and their referrer ids. referrer_id points at another row in the same table. A self-join uses two aliases for those two roles.
step-1.sqlSELECT id, email, country, referrer_id FROM members ORDER BY id;
Join the table to itself. Alias m is the member and r is the referrer. LEFT JOIN keeps members who have no referrer.
step-2.sqlSELECT m.id AS member_id, r.id AS referrer_id FROM members m LEFT JOIN members r ON r.id = m.referrer_id;