Re: Can I use check-constraint to set null?

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Rikard Bosnjakovic <rikard(dot)bosnjakovic(at)gmail(dot)com>
Cc: pgsql-novice(at)postgresql(dot)org
Subject: Re: Can I use check-constraint to set null?
Date: 2010-08-16 18:32:44
Message-ID: 18967.1281983564@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

Rikard Bosnjakovic <rikard(dot)bosnjakovic(at)gmail(dot)com> writes:
> CREATE TABLE test (foo numeric(8,2) CHECK (foo >= 0.0));

> ecdb=> insert into test values (-2.2);
> ERROR: new row for relation "test" violates check constraint "test_foo_check"

> This is expected.

> However, is there a way to insert a null when this check fails,
> instead of returning an error (and thus aborting the insert)?

You could write a BEFORE INSERT trigger that does something like

IF NOT NEW.foo >= 0.0 THEN
NEW.foo := NULL;
END IF;

regards, tom lane

In response to

Browse pgsql-novice by date

  From Date Subject
Next Message Andreas Kretschmer 2010-08-16 18:33:24 Re: Remote Connection to server: Connection Refused
Previous Message Leon Starr 2010-08-16 18:30:08 Re: How to trap invalid enum input exception?