How to prevent redundant relationships in data

database-design

If I want to link users with other users. Would this be a good way to do it:

Relationship diagram

I'm asking because I probably get double data like this if i don't do specific checks:

+------+-------------+
|userId|relatedUserId|
+------+-------------+
|   1  |      2      |
|   1  |      3      |
|   2  |      1      |
|   2  |      3      |
|   3  |      1      |
|   3  |      2      |
+------+-------------+

Best Answer

It sounds like you are describing a mutual relationship such that there is no difference between (1,2) and (2,1). In this case you should design your code to always insert the lower userId as the first value and the higher as the second. Then you can use AlexKuznetsov's suggestion and add a CHECK constraint of (userId<relatedUserId). The code can then catch the duplicate exceptions and ignore them since the relationship already exists.

Note: I flipped the comparison from > to < because the lower number being first makes more sense to me. It works either way and may make more sense the other way in your environment.