user1949387
user1949387

Reputation: 1275

Postgres how can I make 2 numerical fields unique to each other

I am trying to do a following/follower type of concept that many social networks have. I have 2 INT fields called me and following, Those INT fields are composed of users Unique ID. I want to make so that if user 23 is following user 7 or 23->7 then user 23 can not follow user 7 again because the relationship already exists. This picture will clear things up

enter image description here

Notice above the first 2 rows are 31->27 or user 31 is following 27 twice that is redundant. Is there some constraint that I can use to prevent that from happening ? I am using postgres version 9.4

Upvotes: 1

Views: 27

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269563

You can do this by creating a unique index. But not just any unique index, one on expressions:

create unique index unq_t_me_following
    on (least(me, following), greatest(me, following));

Upvotes: 1

Related Questions