Search code examples
sqlpostgresqlcreate-tableexclusion-constraint

How to get unique values from 2 columns in PostgreSQL


i have a column "id_a" and a column "id_b".

"id_a" is an integer[] type.

"id_b" is an int type.

I have to find a way to verify that there are no more values ​​of id_a with the same id_b

For Example:
id_a {3,4,5}    id_b 18

Other Examples:

ERROR:
id_a{3,4,5}  id_b 18 --> because i have already the value of b with the same values of a 

NO ERROR:
id_a{3,4,5}  id_b 19

ANOTHER ERROR:
id_a{3}      id_b 19

NO ERROR:
id_a{6}      id_b 18

Solution

  • you can create an exclusion constraint if you install the btree_gist extension:

    create table data (id_a int[], id_b int);
    
    alter table data
      add constraint check_ids 
      exclude using gist (id_a with &&, id_b with =);
    

    Initial row - no problem

    insert into data (id_a, id_b) values ('{3,4,5}', 18);
    

    Running the above again yields an error as expected.

    The following works:

    insert into data (id_a, id_b) values ('{3,4,5}', 19);
    

    And then:

    insert into data (id_a, id_b) values ('{3}', 19);
    

    will result in an error

    ERROR: conflicting key value violates exclusion constraint "check_ids"

    Online example