Rank a User's Friends by Their Own Outgoing Friendship Count
Company: Meta
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
`Friends` rows `(A, B)` are directed friendships. For each friend of user `user_id = 1`, compute `friend_count` as that friend's number of outgoing friendships (0 if none). Return `user_id`, `name`, `friend_count` ordered by `friend_count` DESC, then `user_id` ASC, limited to 10 rows.
```hint Friends with no friends
Make sure a friend of user 1 who has no outgoing rows still produces an output row, and check what your count returns for that row.
```
### Input Table(s)
`Users` (primary key `user_id`)
| column | type | meaning |
|---|---|---|
| user_id | INT | Unique user identifier |
| name | VARCHAR(100), NOT NULL | User's name |
`Friends` (unique on `(user_id, friend_id)`)
| column | type | meaning |
|---|---|---|
| user_id | INT, NOT NULL | User who has the friendship |
| friend_id | INT, NOT NULL | User they are friends with |
### Output Contract
- Columns, in this order: `user_id` (the friend's id), `name` (the friend's name), `friend_count` (integer number of `Friends` rows where that friend is the `user_id`).
- Order by `friend_count` descending, then `user_id` ascending.
- Return at most 10 rows.
- No rounding is involved.
### Example
`Users`
| user_id | name |
|---|---|
| 1 | Alice |
| 2 | Bob |
| 3 | Charlie |
| 4 | Diana |
| 5 | Eve |
`Friends`
| user_id | friend_id |
|---|---|
| 1 | 2 |
| 1 | 3 |
| 1 | 4 |
| 2 | 3 |
| 2 | 4 |
| 2 | 5 |
| 3 | 4 |
| 4 | 5 |
Expected result
| user_id | name | friend_count |
|---|---|---|
| 2 | Bob | 3 |
| 3 | Charlie | 1 |
| 4 | Diana | 1 |
Alice's friends are Bob, Charlie and Diana. Bob has three outgoing rows, Charlie and Diana have one each, and the tie between Charlie and Diana is broken by `user_id`. Eve is not listed because Alice has no row pointing to her.
### Constraints and Clarifications
- `Users` has at most 10,000 rows and `Friends` at most 100,000 rows.
- `(user_id, friend_id)` is unique in `Friends`, and a user cannot be friends with themselves.
- Friendships are directed. User 1's friends are the `friend_id` values of rows with `user_id = 1`; a row `(5, 1)` alone does not make user 5 a friend of user 1.
- A friend's `friend_count` counts all of their outgoing rows, including a row back to user 1 if one exists.
- A friend with no outgoing rows appears with `friend_count = 0`.
- Ties on `friend_count` are broken by `user_id` ascending, which also decides who gets the last of the 10 places.
Overview: Write a SQL query that finds every friend of one user in a directed friendship table and ranks them by how many friendships they have themselves. It tests self-joins, keeping zero counts with a LEFT JOIN, counting a nullable column, and a tie-break before the row limit.