UNIQUE boolean: only one row may be "true"

From: Randall Lucas <rlucas(at)tercent(dot)net>
To: pgsql-sql(at)postgresql(dot)org
Subject: UNIQUE boolean: only one row may be "true"
Date: 2003-05-06 16:01:20
Message-ID: FA25F27B-7FDB-11D7-A71E-000A957653D6@tercent.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql


Hi folks,

After a late night of SQL hacking, my brain fizzed out:

How shall I create a constraint such that only one row may be 'true'?
Rephrased, may I place a WHERE clause in a UNIQUE constraint, or
alternatively, may I use a CHECK constraint with an aggregate?

Example:

CREATE TABLE thing (
thing_id serial primary key,
thing_group_id int not null references thing_group(thing_group_id),
is_main_thing_p boolean not null default 'f',
-- there may be only one main thing per group:
unique (thing_group_id, is_main_thing_p='t')
-- or else something like:
-- check (count (*) from thing where thing_group_id=NEW.thing_group_id
and is_main_thing_p = 't' <2)
);

Best,

Randall

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Diehl, Jeffrey 2003-05-06 16:28:43 Re: pgsql Replication Proxy (was Re: Replication for a
Previous Message alexandre :: aldeia digital 2003-05-06 15:55:19 pg_stat_activity IP address