Rank Friend Suggestions by Mutual Friend Count in SQL
Last updated: November 29, 2026
Quick Overview
Given a friendships table where each friendship may be stored in only one direction, write SQL that returns each user's top 10 non-friend suggestions ranked by number of mutual friends.
Meta
November 29, 20260
0
0 solved
Given a friendships table where each friendship may be stored in only one direction, write SQL that returns each user's top 10 non-friend suggestions ranked by number of mutual friends.
Mutual-friend counting is the core of a simple People You May Know baseline at Facebook, so it shows up often in Meta SQL rounds. The interviewer checks symmetric edge handling, the self-join through a shared friend, excluding existing friends and the user themselves, and the cost of the join.
What the Interviewer Expects
- Symmetrizes the edge table before joining
- Counts mutual friends with a two-hop self-join
- Excludes the user and existing friends from candidates
- Ranks with a deterministic tie-break and limits to 10 per user
- Discusses the quadratic blow-up from high-degree users
Key Topics to Cover
How to Approach This
- Clarify the schema and expected output format before writing queries.
- Use CTEs (WITH clauses) to break complex queries into readable steps.
- Consider window functions (ROW_NUMBER, RANK, LAG, LEAD) for ranking and sequential analysis.
- Watch for NULLs, duplicates, and edge cases in JOINs and GROUP BY.
- For pandas, prefer vectorized operations over row-by-row iteration.
Possible Follow-up Questions
- How would you weight mutual friends who are themselves very popular?
- How would you restrict to friends added in the last year?
- How would you run this over billions of edges?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice SQL ProblemsSample Answer
Clarify the Data
Table: friendships(user_id, friend_id, created_at). Each friendship may be stored once, as (a, b) or (b, a), so I must make it symmetric. No self-edges are expected, but I will guard against them. O...
Approach
- Symmetrize: union the table with its reverse, so every friendship is two directed rows.
- Two-hop join: user
uto friendx, thenxto friendc. Eachxthat linksuandcis a mutual ...