Postgres constraint ensuring one column of many is present?

前端 未结 6 1503
天命终不由人
天命终不由人 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条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-01 03:58

    Since PostgreSQL 9.6 you have the num_nonnulls and num_nulls comparison functions that accept any number of VARIADIC arguments.

    For example, this would make sure exactly one of the three columns is not null.

    ALTER TABLE your_table
    ADD CONSTRAINT chk_only_one_is_not_null CHECK (num_nonnulls(col1, col2, col3) = 1);
    

提交回复
热议问题