I have two tables; friends and users.
The Users table, slightly simplified:
CREATE TABLE users (
id bigserial NOT NULL,
fname text,
lname text,
username text,
created timestamp without time zone DEFAULT now(),
CONSTRAINT users_pkey PRIMARY KEY (id)
)
And the Friends table is a join table
CREATE TABLE friends
(
user_id bigint,
friend_id bigint,
accepted boolean DEFAULT false
)
So the friends table just maps one user to another, so user 1 can be friends with user 2.
My question: How can I constrain the table so that two pairs (1, 2) , (2,1) do not get inserted into the table?
I know I can do unique (user_id , friend_id)
to prevent duplicate rows like (1,2) from being inserted...
But how do I prevent (2, 1) from being inserted if (1, 2) already exists?