Database – DB Schema design : single table with more columns vs multiple tables with fewer colomns

databasedatabase-designMySQL

What would be better DB design for a social network website.
A single table with more columns and less rows or multiple table with fewer columns but more rows.

For example:
User can post an update on their wall or in a group.

Two DB designs that I could think of are:

1)
UserPosts: id, userId, post, datetime
UserGroupPost: id, groupId, userId, post, datetime

Potentail problem : Might require joins, which can (in future) be a slow query.

2)
Posts: id, userId, groupId, post, datetime
(where groupid would be null if user posts on their wall)

Potential Problem : Looping over large dataset could take a (long)time.

Where can I get better performance when data increases?
Is there any other(better) way?

Best Answer

Any thing ("Entity") that can exist on its own, independently of anything else, should have its own table.

User: id, name, hashed_password, join_date, birth_date

Group: id, name

Relationships between things require generally require "linking" tables.

Post: id, user_id, group_id, post_date, post_title, post_content

The key to success is proper indexing of any field where you join between tables or on which you filter results.
Also, consider using a dummy (non-NULL) Group value for posts to a user's own "wall" - NULLs are often not included in indexes, which will make your queries for these posts run [far] slower.

Related Topic