I want to have a table with columns: id, user_id1, and user_id2.
basically this will resprsent a friend graph with the link representing that user1 is friends with user2 AND vice versa.
my setup gets a single user and then a list of their friends. given that I don’t want to have extra entries in my table how shoudl I handle this?
I want to do something like: insert into friendship (user_id1, user_id2) values (<id1>, <id2>) where ...
but I’m not sure how to do conditional logic like that in SQL
You could force
user_id1to always be less thanuser_id2with a CHECK constraint:Presumably people aren’t allowed to be their own friends. And then make sure the IDs are in the right order before you INSERT. When extracting a list of friends, you’d still have to check both columns though:
where
Xis, of course, the person you’re interested in. And to see if two people are friends, just arrange their IDs in the right order and SELECT away.