简体   繁体   中英

UNIQUE constraint across multiple columns

I need a UNIQUE constraint which spans 2 columns, but allows NULL values anywhere. I have this :

CREATE TABLE table_1{
  COLUMN a INT SET DEFAULT NULL,
  COLUMN b INT SET DEFAULT NULL
 -- <insert constraint here>
}

Some examples:

a  b
1  2
3  4
valid
a  b
1  1
2  3
invalid
a  b
1  2
1  3
invalid
a  b
1  2
3  1
invalid
a  b
1  2
3  NULL
valid
a  b
1  2
3  NULL
4 NULL
NULL 5
valid

modification of @a_horse_with_no_name suggestion

create table table_1(a int default null, b int default null);
ALTER TABLE table_1
    ADD CONSTRAINT excl exclude using gist ( (array_remove(array[a, b],NULL)) with &&);

this will work fine with NULLable columns

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM