Postgres constraint ensuring one column of many is present?

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

    A bit clumsy, but should do the trick:

    create table foo
    (
       col1 integer,
       col2 integer,
       col3 integer,
       constraint one_is_not_null check 
            (    (col1 is not null and col2 is null and col3 is null) 
              or (col1 is null and col2 is not null and col3 is null)
              or (col1 is null and col2 is null and col3 is not null)
            )
    )
    

提交回复
热议问题