Full answer
A follow is a directed edge: Ana follows Ben does not mean Ben follows Ana. A mutual pair needs both edges.
sql
CREATE TABLE follows (follower TEXT, followee TEXT, PRIMARY KEY (follower, followee));
INSERT INTO follows VALUES ('Ana','Ben'),('Ben','Ana'),('Ana','Chen'),('Chen','Dara'),('Dara','Chen'),('Ben','Dara');Join the table to itself, looking for the reverse edge of each row:
sql
SELECT a.follower, a.followee
FROM follows a
JOIN follows b ON b.follower = a.followee AND b.followee = a.follower
ORDER BY a.follower, a.followee;| follower | followee |
|---|---|
| Ana | Ben |
| Ben | Ana |
| Chen | Dara |
| Dara | Chen |
Each mutual pair shows up twice, once starting from each side. Keep one copy by ordering the pair:
sql
SELECT a.follower AS user_1, a.followee AS user_2
FROM follows a
JOIN follows b ON b.follower = a.followee AND b.followee = a.follower
WHERE a.follower < a.followee
ORDER BY user_1;| user_1 | user_2 |
|---|---|
| Ana | Ben |
| Chen | Dara |
Ana and Ben follow each other, and so do Chen and Dara. Ana follows Chen but Chen does not follow back, so that pair is not mutual.
An index on (follower, followee) makes the reverse lookup cheap: for each row, the database seeks the index for the swapped pair. The primary key here already provides it. If the table may contain duplicate follow rows, the result may repeat; a primary key on the pair prevents that.
sql
CREATE TABLE follows (follower TEXT, followee TEXT, PRIMARY KEY (follower, followee));
INSERT INTO follows VALUES ('Ana','Ben'),('Ben','Ana'),('Ana','Chen'),('Chen','Dara'),('Dara','Chen'),('Ben','Dara');
SELECT a.follower, a.followee
FROM follows a
JOIN follows b ON b.follower = a.followee AND b.followee = a.follower
ORDER BY a.follower, a.followee;
SELECT a.follower AS user_1, a.followee AS user_2
FROM follows a
JOIN follows b ON b.follower = a.followee AND b.followee = a.follower
WHERE a.follower < a.followee
ORDER BY user_1;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- Mutual means both directed edges exist
- Self join on swapped columns finds the reverse edge
- a.follower < a.followee keeps one copy of each pair
- A key on (follower, followee) supports the lookup and prevents duplicates
Common mistakes
- Forgetting the ordering condition and reporting each pair twice
- Joining on only one column and matching unrelated edges
Follow-ups
- How would you find users followed by someone they do not follow back?
- How would you count mutual friends for a pair of users?
Tips
- Draw the two arrows; it makes the join condition obvious