Full answer
text
friendships(user_id, friend_id, PRIMARY KEY (user_id, friend_id)) -- both directions stored
SELECT f2.friend_id AS candidate, COUNT(*) AS mutual_friends
FROM friendships f1
JOIN friendships f2 ON f2.user_id = f1.friend_id
WHERE f1.user_id = :me
AND f2.friend_id <> :me
AND NOT EXISTS (SELECT 1 FROM friendships x WHERE x.user_id = :me AND x.friend_id = f2.friend_id)
GROUP BY f2.friend_id
ORDER BY mutual_friends DESC
LIMIT 20;Storing both directions makes listing a user's friends a simple index range on user_id and keeps queries symmetric; a CHECK or trigger keeps pairs in sync.
Scaling: a user with 500 friends who each have 500 friends gives 250,000 rows to group. Batch jobs that precompute top suggestions nightly, sampling, or a graph database for deeper traversals are common answers. Blocked users and declined suggestions need their own exclusion tables. The query is illustrative and was not run here.
Key points
- Store friendships in both directions
- Self-join for the second hop
- Exclude self and existing friends
- Rank by mutual friends
- Precompute at scale
Common mistakes
- Storing each friendship once and writing OR conditions everywhere
- Running deep traversals live for every page view
Follow-ups
- How would you include third-degree connections?
- When would a graph database be better?
Tips
- Explain the growth of the second hop