Re: help writing a constraint

From: Alvaro Herrera <alvherre(at)atentus(dot)com>
To: Gregory Seidman <gss+pg(at)cs(dot)brown(dot)edu>
Cc: PostgreSQL general mailing list <pgsql-general(at)postgresql(dot)org>
Subject: Re: help writing a constraint
Date: 2002-08-11 20:10:24
Message-ID: Pine.LNX.4.44.0208111604280.13909-100000@cm-lcon1-46-187.cm.vtr.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Gregory Seidman dijo:

>
> I need to constrain this so that for any given row, it either hasBar or
> hasBaz, or neither, but not both. I'm not entirely clear on how to write
> constraints, though. Is the following correct (within the CREATE)?
>
> CHECK (hasBar IS NULL OR hasBaz IS NULL)

CREATE TABLE Foo (
id SERIAL not null,
hasBar integer default null REFERENCES Bar,
hasBaz integer default null REFERENCES Baz,
primary key (id),
CHECK (hasBar IS NULL OR hasBaz IS NULL)
);

Why don't you try it out before asking? You were perfectly right.

You can also give a name to constraints to get more meaningful messages
(useful if you have lots of constraints):

CREATE TABLE Foo (
id SERIAL not null,
hasBar integer default null REFERENCES Bar,
hasBaz integer default null REFERENCES Baz,
primary key (id),
constraint onlyOne CHECK (hasBar IS NULL OR hasBaz IS NULL)
);

--
Alvaro Herrera (<alvherre[a]atentus.com>)
"Siempre hay que alimentar a los dioses, aunque la tierra este seca" (Orual)

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Patrick Nelson 2002-08-11 20:16:21 After upgrade pg_dumpall fails
Previous Message Joe Conway 2002-08-11 20:09:43 Re: [GENERAL] workaround for lack of REPLACE() function