You can create an index on an expression, in this case least()
and greatest()
:
create unique index idx_obj1_obj2 on table(least(Object1, Object2), greatest(Object1, Object2));
Note: there is one slight weirdness if the columns allow NULL
values. In that case, the same value would only be allowed once, regardless of the column it is in. This can be fixed with a more complicated expression, if it is actually a problem.