Postgresql enforce unique two-way combination of columns

A variation on Neil’s solution which doesn’t need an extension is:

create table friendz (
  from_id int,
  to_id int
);

create unique index ifriendz on friendz(greatest(from_id,to_id), least(from_id,to_id));

Neil’s solution lets you use an arbitrary number of columns though.

We’re both relying on using expressions to build the index which is documented
https://www.postgresql.org/docs/current/indexes-expressional.html

Leave a Comment