You are designing a database schema for a social media app. How would you model a "follower" relationship (many-to-many)? Please what tables would you need, what is a "join table" (or linking table), design the schema for the join table. What columns and foreign keys would it have, and write a SQL query to find all the followers of a given user.
Assistant
We are designing a social media app and need to model a "follower" relationship, which is many-to-many.
In a many-to-many relationship, we need three tables:
The two main tables (e.g., users) that are related.
A join table (also called linking table or associative table) that connects the two.
However, note that in the context of followers, it's a directed relationship (user A follows user B, but user B does not necessarily follow user A).
So we can think of it as a relationship from a follower (follower_id) to a followee (followee_id). Both are references to the same users table.
Steps:
We have a users table (if not already existing, but we assume it exists).
We create a follows table (the join table) that has at least two foreign keys:
follower_id -> references users(id)
followee_id -> references users(id)
We might also want to store additional information, such as the timestamp when the follow happened.
To enforce that a user cannot follow the same user twice, we can set a composite primary key on (follower_id, followee_id) or a unique constraint on these two columns.
We might also want to add an index on followee_id to quickly find who a user is followed by.
The follows table does not need its own auto-increment primary key because the combination of follower_id and followee_id is unique and can serve as the primary key.
Let's design the tables:
Table: users
id (primary key)
... other columns (username, email, etc.)
Table: follows
follower_id (foreign key to users.id)
followee_id (foreign key to users.id)
created_at (timestamp, default current timestamp)
Primary key: (follower_id, followee_id)
We can also create an index on followee_id for queries that look up who follows a given user.
Now, to find all the followers of a given user (say, user with id = X), we need to find all records in the follows table where followee_id = X.
Then, we can join with the users table to get the details of the followers.
Example SQL query:
SELECT u.*
FROM users u
JOIN follows f ON u.id = f.follower_id
WHERE f.followee_id = X;
However, note: the above query returns the users who follow user X.
Alternatively, if we want to get the follower relationships (including the timestamp) we might do:
SELECT f.follower_id, u.username, f.created_at
FROM follows f
JOIN users u ON f.follower_id = u.id
WHERE f.followee_id = X;
But the question asks for "all the followers of a given user", so we want the user records of the followers.
Let's write the full SQL to create the tables and then the query.
Note: We assume the users table already exists.
If we are creating the follows table from scratch:
CREATE TABLE follows (
follower_id INT NOT NULL,
followee_id INT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (follower_id, followee_id),
FOREIGN KEY (follower_id) REFERENCES users(id) ON DELETE CASCADE,
FOREIGN KEY (followee_id) REFERENCES users(id) ON DELETE CASCADE
);
We might also want to create an index on followee_id for performance:
CREATE INDEX idx_follows_followee_id ON follows(followee_id);
Now, the query to find all followers of a user with id = 123:
SELECT u.*
FROM users u
INNER JOIN follows f ON u.id = f.follower_id
WHERE f.followee_id = 123;
However, note that the above query will return the user records of the followers. If we only need the IDs, we can adjust.
But the question says "all the followers", which I interpret as the user records of the followers.
If we want to include the follow date, we can adjust the SELECT.
Let me adjust to include the created_at:
SELECT u.*, f.created_at AS followed_at
FROM users u
INNER JOIN follows f ON u.id = f.follower_id
WHERE f.followee_id = 123;
But note: the original users table might have many columns, and we are selecting all of them plus the followed_at.
Alternatively, if we don't want all columns from users, we can specify.
However, the question does not specify the exact output, so I'll provide a general one.
Important: We must consider that the user with id 123 might have no followers, then the query returns an empty set.
Let me write the complete answer:
Table creation for follows (assuming users table exists with an integer primary key named 'id'):
CREATE TABLE follows (
follower_id INT NOT NULL,
followee_id INT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (follower_id, followee_id),
FOREIGN KEY (follower_id) REFERENCES users(id) ON DELETE CASCADE,
FOREIGN KEY (followee_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE INDEX idx_follows_followee_id ON follows(followee_id);
Query to find all followers of user with id = 123:
SELECT u.*
FROM users u
JOIN follows f ON u.id = f.follower_id
WHERE f.followee_id = 123;
If we want to order by the follow date (most recent first):
SELECT u.*, f.created_at AS followed_at
FROM users u
JOIN follows f ON u.id = f.follower_id
WHERE f.followee_id = 123
ORDER BY f.created_at DESC;
But note: the question does not specify ordering.
So the basic query without ordering is the first one.
However, note that the relationship is directed: the follower is the one who initiates the follow.
Let me clarify:
In the follows table, follower_id is the user who follows, and followee_id is the user being followed.
Therefore, to get the followers of user X (the followees of X in reverse? Wait, let's think:
If user A follows user B, then:
follower_id = A, followee_id = B.
To get the followers of user B (i.e., all users who follow B), we look for records where followee_id = B.
So in the query above, we are looking for followee_id = 123, meaning we are getting the users who follow user 123.
That is correct.
So the query is:
SELECT u.*
FROM users u
JOIN follows f ON u.id = f.follower_id
WHERE f.followee_id = 123;
This returns all users (u) who follow the user with id 123.
If we want to get the users that a given user follows (the opposite), then we would switch:
SELECT u.*
FROM users u
JOIN follows f ON u.id = f.followee_id
WHERE f.follower_id = 123;
But the question asks for followers, so we stick with the first.
Let me write the answer accordingly.
For a many-to-many "follower" relationship in a social media app (where one user can follow many users and be followed by many users), here’s the complete design:
1. Core Tables
You need two main tables plus a join table:
users Table (already exists)
Column
Type
Description
id
BIGINT (PK)
Unique user ID
username
VARCHAR(50)
Unique username
...
...
Other user fields (email, etc.)
2. Join Table: follows
This linking table resolves the many-to-many relationship by storing pairs of user IDs representing a "follow" action.
Schema Design:
sql
CREATE TABLE follows (
follower_id BIGINT NOT NULL, -- User who initiates the follow
followee_id BIGINT NOT NULL, -- User being followed
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, -- When the follow occurred
PRIMARY KEY (follower_id, followee_id), -- Composite PK prevents duplicate follows
FOREIGN KEY (follower_id) REFERENCES users(id) ON DELETE CASCADE,
FOREIGN KEY (followee_id) REFERENCES users(id) ON DELETE CASCADE
);
Efficient lookups for "who does X follow?" (WHERE follower_id = ?).
Foreign Keys enforce referential integrity:
ON DELETE CASCADE: If a user is deleted, their follows/followers are automatically removed.
created_at tracks when the follow happened (useful for timeline/feed ordering).
Index Recommendation: Add an index on followee_id for fast "followers of X" queries:
sql
CREATE INDEX idx_follows_followee ON follows(followee_id);
3. SQL Query: Find All Followers of a Given User
Given a user ID (e.g., 123), retrieve all users who follow them:
sql
SELECT u.* -- Or select specific columns: u.id, u.username, f.created_at
FROM users u
JOIN follows f ON u.id = f.follower_id
WHERE f.followee_id = 123
ORDER BY f.created_at DESC; -- Optional: newest followers first
Explanation:
JOIN follows f ON u.id = f.follower_id: Match users to rows where they are the follower.
WHERE f.followee_id = 123: Filter for follows where the target user (followee) is 123.
ORDER BY f.created_at DESC: Returns followers in reverse chronological order (most recent first).
4. Example Data
users:
id
username
1
alice
2
bob
3
charlie
follows:
follower_id
followee_id
created_at
1
2
2023-10-01 10:00:00
1
3
2023-10-02 11:00:00
2
3
2023-10-03 12:00:00
Query: SELECT * FROM ... WHERE followee_id = 3 Result: Followers of charlie (id=3) are alice (id=1) and bob (id=2).
5. Key Notes
Direction Matters: The relationship is directed (follower → followee).
To get who a user follows: Swap the WHERE clause to f.follower_id = ?.
Performance: The composite PK + index on followee_id ensures fast lookups for both "followers of X" and "who does X follow?".
Scalability: For massive scale (e.g., millions of follows), consider:
Partitioning the follows table by follower_id or followee_id.
Caching follower counts in the users table (denormalization).
6. Optional Enhancements
Add to follows table if needed:
status (e.g., 'pending' for private accounts).
source (e.g., 'search', 'profile').
Unique constraint on (follower_id, followee_id) if using a surrogate PK (not recommended here).
This design is standard for follower systems (used by Twitter, Instagram, etc.) and balances normalization with query efficiency.