Find Followers Count - Problem

You are given a Followers table that contains information about user-follower relationships in a social media app.

Table: Followers

  • user_id (int): The ID of the user being followed
  • follower_id (int): The ID of the user who is following
  • The combination (user_id, follower_id) is the primary key

Write a SQL solution to find the number of followers for each user. Return the result table ordered by user_id in ascending order.

Table Schema

Followers
Column Name Type Description
user_id PK int ID of the user being followed
follower_id PK int ID of the user who is following
Primary Key: (user_id, follower_id)
Note: Each row represents a follower relationship where follower_id follows user_id

Input & Output

Example 1 — Multiple Users with Followers
Input Table:
user_id follower_id
1 3
2 3
2 1
Output:
user_id followers_count
1 1
2 2
💡 Note:

User 1 has 1 follower (user 3). User 2 has 2 followers (users 3 and 1). Results are ordered by user_id ascending.

Example 2 — Single User Multiple Followers
Input Table:
user_id follower_id
1 2
1 3
1 4
Output:
user_id followers_count
1 3
💡 Note:

User 1 has 3 followers (users 2, 3, and 4). The GROUP BY aggregates all followers for user 1.

Example 3 — Each User One Follower
Input Table:
user_id follower_id
1 2
3 4
Output:
user_id followers_count
1 1
3 1
💡 Note:

User 1 has 1 follower (user 2) and user 3 has 1 follower (user 4). Results ordered by user_id.

Constraints

  • 1 ≤ user_id, follower_id ≤ 1000
  • user_id != follower_id (users cannot follow themselves)

Visualization

Tap to expand
Find Followers Count INPUT Followers Table user_id follower_id 0 1 1 0 2 0 2 1 User Relationships U0 U1 U2 Primary Key: (user_id, follower_id) ALGORITHM STEPS 1 GROUP BY user_id Group all rows by user_id 2 COUNT followers Count follower_id per group 3 ORDER BY user_id Sort results ascending 4 Return Result Output user_id and count SQL Query: SELECT user_id, COUNT(follower_id) AS followers_count FROM Followers GROUP BY user_id ORDER BY user_id; FINAL RESULT Output Table user_id followers_count 0 1 1 1 2 2 Followers Summary User 0 1 User 1 1 User 2 2 OK - Done! Key Insight: The GROUP BY clause aggregates rows by user_id, while COUNT() tallies follower_id entries per group. Since (user_id, follower_id) is the primary key, each combination is unique, ensuring accurate counts. TutorialsPoint - Find Followers Count | Optimal Solution
Asked in
Facebook 28 Instagram 22 Twitter 19
25.4K Views
High Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen