Given the following three columns in a Postgres database: first, second, third; how can I create a constraint such that permutations are unique?
E.g. If ('foo', 'bar', 'shiz')
exist in the db, ('bar', 'shiz', 'foo')
would be excluded as non-unique.
For only three columns this unique index using only basic expressions should perform very well. No additional modules like hstore or custom function needed:
SQL fiddle
Also needs the least disk space:
Numbers are bytes for index row in the example in the fiddle, measured with
pg_column_size()
. My example uses only single characters, the difference in size is constant.You can do this by creating a unique index on a function which returns a sorted array of the values in the columns:
Suggestion from co-worker, variation of @julien's idea:
Sort the terms alphabetically and place a delimiter on either side of each term. Concatenate them and place them in a separate field that becomes the primary key.
Why the delimiter? So that, "a", "aa", "aaa" and "aa", "aa", "aa" can both be inserted.
You could use hstore to create the unique index:
Fiddle
UPDATE
Actually
might be a better idea since it will work the same but should take less space (fiddle).