postgres add constraint to ensure one column is not null if another column is not null

StackOverflow https://stackoverflow.com/questions/23326806

  •  10-07-2023
  •  | 
  •  

Pergunta

Postgres 9.3

I have two integer type columns 'a' and 'b'. Valid options are:

  • 'a' is null, 'b' is null
  • 'a' is not null, 'b' is null
  • 'a' is not null, 'b' is not null

I'm trying to add a check/constraint which prevents the invalid option:

  • 'a' is null, 'b' is not null

I'd be grateful for any help.

Thanks in advance Dan

Foi útil?

Solução

Looks like your condition is actually a logical implication: if a is null then b is null. From our symbolic logic course (PHIL 140 in my case), we know that:

(P -> Q) <-> (-P | Q)

where -> is implication and <-> is logical equivalence.

Applying that to our implication and SQLizing it yields:

a is not null or b is null

so a simple check(a is not null or b is null) constraint is sufficient.

Demo: http://sqlfiddle.com/#!15/bebee/1

Outras dicas

create table t (
    a int,
    b int,
    check (
        a is null and b is null
        or
        a is not null and b is null
        or
        a is not null and b is not null
    )
);

insert into t (a, b) values
(null, null),
(1, null),
(1, 1),
(null, 1);
ERROR:  new row for relation "t" violates check constraint "t_check"
DETAIL:  Failing row contains (null, 1).
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top