How can I efficiently create a unique index on two fields in a table like this: create table t (a integer, b integer);
where any unique combination of two different numbers cannot appear more than once on the same row in the table.
In order words if a row exists such that a=1 and b=2, another row cannot exist where a=2 and b=1 or a=1 and b=2. In other words two numbers cannot appear together more than once in any order.
I have no idea what such a constraint is called, hence the ‘two-sided unique index’ name in the title.
Update: If I have a composite key on columns (a,b), and a row (1,2) exists in the database, it is possible to insert another row (2,1) without an error. What I’m looking for is a way to prevent the same pair of numbers from being used more than once in any order…
How about controlling what goes into the table so that you always store the smallest number into the first column and the largest one in the second? As long as it ‘means’ the same thing of course. It’s probably less expensive to do it before it even gets to the database.
If this is impossible, you could save the fields as is but have them duplicated in numerical order into two OTHER fields, on which you would create the primary key (pseudo code-ish) :
This could easily be done with a trigger (as in Ronald’s response) or handled higher up, in the application.