Re: interesting check constraint behavior

From: "Gauthier, Dave" <dave(dot)gauthier(at)intel(dot)com>
To: Alban Hertroys <dalroi(at)solfertje(dot)student(dot)utwente(dot)nl>
Cc: "pgsql-general(at)postgresql(dot)org" <pgsql-general(at)postgresql(dot)org>
Subject: Re: interesting check constraint behavior
Date: 2010-01-07 14:22:03
Message-ID: 482E80323A35A54498B8B70FF2B879800438460407@azsmsx504.amr.corp.intel.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Both suggestions (exclude the 'null' from the list, and include "or col1 is null") work.

And if I ever wanted to require that col1 is not null, just add that as a separate constraint.

Thanks guys for the advise and explanation !

-----Original Message-----
From: Alban Hertroys [mailto:dalroi(at)solfertje(dot)student(dot)utwente(dot)nl]
Sent: Thursday, January 07, 2010 5:49 AM
To: Gauthier, Dave
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: [GENERAL] interesting check constraint behavior

On 7 Jan 2010, at 24:12, Gauthier, Dave wrote:

> 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.

As Tom already explained, "value in ('yada', 'yada', null)" evaluates to null. You'll need to make sure your check expression evaluates to either true or false - not null.

I guess you need: check(col1 in ('a', 'b', 'c') or col1 is null)

Alban Hertroys

--
If you can't see the forest for the trees,
cut the trees and you'll see there is no forest.

!DSPAM:1015,4b45bc2510731992717809!

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Merlin Moncure 2010-01-07 14:47:51 Re: Use C++ to iterate integer array returned from stored procedure
Previous Message Konrad Garus 2010-01-07 13:58:54 Re: Rows missing from table despite FK constraint