Postgres constraint ensuring one column of many is present?

前端 未结 6 1511
天命终不由人
天命终不由人 2021-02-01 03:01

What are good ways to add a constraint to PostgreSQL to check that exactly one column (from a set of columns) contains a non-null value?

Update: It is likely th

6条回答
  •  梦毁少年i
    2021-02-01 03:47

    As hinted by mu is too short:

    alter table t
    add constraint only_one_null check (
        (col1 is not null)::integer + (col2 is not null)::integer = 1
    )
    

提交回复
热议问题