Re: interesting check constraint behavior

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: "Gauthier, Dave" <dave(dot)gauthier(at)intel(dot)com>
Cc: "pgsql-general(at)postgresql(dot)org" <pgsql-general(at)postgresql(dot)org>
Subject: Re: interesting check constraint behavior
Date: 2010-01-06 23:38:56
Message-ID: 28792.1262821136@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

"Gauthier, Dave" <dave(dot)gauthier(at)intel(dot)com> writes:
> thedb=# create table foo (col1 text, constraint chk check (col1 in ('a','b','c',null)));
> CREATE TABLE
> thedb=# insert into foo (col1) values ('xxx');
> INSERT 0 1

> Hmmmm... I would have thought that this would have violated the constraint because 'xxx' is not null and nit one of the allowed values.

Nulls are tricky. That constraint is equivalent to

col1 = 'a' or col1 = 'b' or col1 = 'c' or col1 = null

The last reduces to null (not false), so you get either TRUE or NULL out
of the OR condition. CHECK constraints are defined to not fail on a null
result (which is not terribly consistent, but it's what the spec says).
So basically that check constraint will never fail.

> Is there a different way I can allow for a static set of values AND null too?

Plain old check (col1 in ('a','b','c')) would work that way. If you
actually want to force it to be non-null, you have to say that
explicitly; usually people use a separate NOT NULL constraint for that.

regards, tom lane

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Iain Barnett 2010-01-07 01:01:39 How to call SETOF function?
Previous Message Gauthier, Dave 2010-01-06 23:12:56 interesting check constraint behavior