Search code examples
sqlpostgresqlcreate-tablecheck-constraints

Conditional Not Null Constraint


Is there a way to model the following behaviour with constraint checks (or other functions) in postgres SQL:

I have two columns:

  • oncost (boolean)
  • oncostdescription (varchar)

If oncost is true, i want oncostdescription to be mandatory (NOT NULL, NOT EMPTY)

If concost is false, i want oncostdescription not to be mandatory (NULL, EMPTY)

EDIT:
I forgot to state my postgres version being lower than 12.
Some folks here came up with a cool feature called generated columns.
Seems pretty cool. But only if you have 12+


Solution

  • You can use a check constraint:

    create table mytable (
        oncost boolean
        oncostdescription varchar(50),
        constraint ck_mytable check(
            not oncost 
            or not (oncostdescription is null or oncostdescription = '')
        )
    )
    

    This phrases as: either the boolean flag is false, or the description is neither null nor empty.

    You could also express this as:

    create table mytable (
        oncost boolean
        oncostdescription varchar(50),
        constraint ck_mytable check(
            not (
                oncost 
                and (oncostdescription is null or oncostdescription = '')
            )
        )
    )