1

Suppose we have this database design

Users table:
- id
- name

Friends table:
- id
- user_id
- friend_user_id

Let's say USER 1 befriended USER 2, this is what my application logic will execute:

INSERT INTO friends (user_id, friend_user_id) VALUES (1, 2);
INSERT INTO friends (user_id, friend_user_id) VALUES (2, 1);

For the retrieval of the USER 1 friends, we simply query this:

SELECT * FROM friends WHERE user_id = 1

Is it a bad idea to make redundant rows when friending users?

What I am trying to avoid here is not to store the friendship in a single row and keep guessing in every query which column the user is in:

SELECT * FROM friends WHERE user_id = 1 OR friend_user_id = 1

The latter made my application logic very complicated in some cases.

6
  • "friend" type relationships are a great use case for a graph database, rather than a purely relational model. Have you considered using graph for your relationship model?
    – AMtwo
    Commented Nov 4, 2021 at 16:54
  • That would be ideal. Unfortunately, our app is based on a relational database and we can't just switch like that. Appreciate your suggestion.
    – parse
    Commented Nov 4, 2021 at 17:05
  • 2
    You might want to tag your existing database engine, if that's a limitation. Some RDMBSs have graph support, so you may still be able to use graph, depending on what DB engine you're tied to.
    – AMtwo
    Commented Nov 4, 2021 at 17:39
  • 2
    Side note: friends table probably doesn't need an id column Commented Nov 4, 2021 at 22:28
  • I assume in this case that "friendship" for the purposes of this example is always mutual?
    – user212533
    Commented Nov 5, 2021 at 16:34

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.