Postgres constraint ensuring one column of many is present?

前端 未结 6 1506
天命终不由人
天命终不由人 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:34

    Here's a solution using the built-in array functions:

    ALTER TABLE your_table
    ADD chk_only_one_is_not_null CHECK (array_length(array_remove(ARRAY[col1, col2, col3], NULL), 1) = 1);
    

提交回复
热议问题