runtime
22 / 88

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 · keyemailtextcountrytextjoined_attextreferrer_idinteger
1 ALICE@Example.com US2025-01-01NULL
2ben@example.comUS2025-01-021
3 Cara@example.comGB2025-01-031
4dev@example.com IN2025-01-042
5NULLCA2025-01-05NULL

showing 5 of 8 rows

example

The idea in one query. Press Run to see what it returns; running examples never affects your progress.

example.sql
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.

  1. 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.sql
    SELECT id, email, country, referrer_id
    FROM members
    ORDER BY id;
  2. 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.sql
    SELECT m.id AS member_id, r.id AS referrer_id
    FROM members m
    LEFT JOIN members r ON r.id = m.referrer_id;

challenge 1

Return member_id and referrer_id for every member, keeping NULL when no referrer exists.

Return member_idreferrer_idany row order

challenge-1.sql
 
To master this lesson, solve both challenges without hints and pass the concept check. 3 of 3 to go.