Re: database constraints - Mailing list pgsql-general

From David Fetter
Subject Re: database constraints
Date
Msg-id 20041006153849.GB30061@fetter.org
Whole thread Raw
In response to database constraints  (Ben <bench@silentmedia.com>)
Responses Re: database constraints  ("Joshua D. Drake" <jd@commandprompt.com>)
List pgsql-general
On Wed, Oct 06, 2004 at 08:23:11AM -0700, Ben wrote:
> If I have have the table:
>
> create table foo
> (
>     a int references bar(id),
>     b int references baz(id)
> )
>
> ... how do I make sure one and only one of the columns a and b are
> non-null?

You could write it like this:

CREATE TABLE foo
(
    a INT REFERENCES bar(id),
    b INT REFERENCES baz(id),
    CHECK((a IS NULL AND b IS NOT NULL) OR (a IS NOT NULL AND b IS NULL))
);

> Is it even reasonable?

What's "reasonable?" ;)

BTW, "id" is a terrible name for a column.  Better call it foo_id.

Cheers,
D
--
David Fetter david@fetter.org http://fetter.org/
phone: +1 510 893 6100   mobile: +1 415 235 3778

Remember to vote!

pgsql-general by date:

Previous
From: sklassen@commandprompt.com
Date:
Subject: Re: database constraints
Next
From: Alessandro Vincelli
Date:
Subject: passing new.* in trigger