Find Followers Count
Preview mode. Log in to edit, run, submit, and save progress.
Medium
Description
You have a Followers table where each row represents that a user (follower_id) follows another user (user_id). Write a SQL query to find the number of followers for each user. Return the result ordered by user_id ascending. (user_id, follower_id) is the primary key.
Database Schema
Followers
| Column Name | Type | Description |
|---|---|---|
| user_id | INT | The user being followed |
| follower_id | INT | The user who follows |
Example
Followers
| user_id | follower_id |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 2 | 1 |
Output
| user_id | followers_count |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 2 |
Explanation:
User 0 is followed by user 1. User 1 is followed by user 0. User 2 is followed by users 0 and 1.
Approach hint
Start with a simple approach, explain the trade-off, then move toward a cleaner or more scalable solution.
Common mistake
Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.
SQL Editor
Loading...
Followers
| user_id | follower_id |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 2 | 1 |
Output
| user_id | followers_count |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 2 |