Is it always a bad practice to have circular relationships in your database design

3.3k Views Asked by At

I don't know how to solve this issue I have the following relationship

user has -> many posts

one posts has -> many comments

one comment has-> one user (owner)

enter image description here

I keep reading this argument by database designers, that this is how it shouldn't be done, but I never read any solutions to these issues, example:

This month, instead of starting with an idea and creating a model to support the concept, I'll analyze a poor design construct: a situation I call the circular reference. A circular reference is a recursive condition in which one table references a second table, which in turn references the first table.

Is it okay to have a circular reference in this case?

2

There are 2 best solutions below

0
On BEST ANSWER

I agree with the comment from @DavidAldridge:

The example that you give is not circular, because both the comment and the post are children of the user, and the comment is also a child of the post -- the relationship between user and post is not the way you describe it or draw it, and in fact the user "has many" comments and the comment "belongs to" the user. For a circular dependency you would need the user to be a child of the post.

I edited the image in the question to help explain what the comment is indicating:

Database Diagram

As far as circular references in databases go, you can build them and simple queries and updates will work, but once you need more complex joins you end up creating variations of Cartesian joins and quickly consume a lot of memory and the query results might never come back.

A circular reference is not the same as a self-referencing relationship. Self-referencing tables are a common sight in database design. You can find a simple example here on Self-Referencing Tables or a full tutorial on all Reference Types including Self-Reference.

0
On

If the two "users" had the same value, I would argue that you have violated the "no redundant info" principle. But, the "owner" of the comment is not necessarily the "owner" of the post. So, you are not storing the same user redundantly.

Relations do not have to be in the form of a Tree. If there were some rule that relations had to be only DAGs (Directed Acyclical Graphs), then the question makes sense.

Lets look at the data a different way. You have Entities: Users, Posts, Comments. You have the relationships you mentioned. So, who cares about "circular"?

You could even have "users" "married" to each other. Can't get much more circular than that!

But, then, we should not be doing your homework, especially more than a year late.