Unique constraint for permutations across multiple columns

前端 未结 4 1462
抹茶落季
抹茶落季 2021-01-17 18:33

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

4条回答
  •  离开以前
    2021-01-17 19:24

    You can do this by creating a unique index on a function which returns a sorted array of the values in the columns:

    CREATE OR REPLACE FUNCTION sorted_array(anyarray)
    RETURNS anyarray
    AS $BODY$
      SELECT array_agg(x) FROM (SELECT unnest($1) AS x FROM test ORDER BY x) AS y;
    $BODY$
    LANGUAGE sql IMMUTABLE;
    
    CREATE UNIQUE index ON test (sorted_array(array[first,second,third]));
    

提交回复
热议问题