pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Bruno Wolff III <bruno@wolff.to>
To: Randall Lucas <rlucas@tercent.net>
Cc: pgsql-sql@postgresql.org
Subject: Re: UNIQUE boolean: only one row may be "true"
Date: Tue, 6 May 2003 12:23:54 -0500
Message-ID: <20030506172354.GA21510@wolff.to> (raw)
In-Reply-To: <FA25F27B-7FDB-11D7-A71E-000A957653D6@tercent.net>
References: <FA25F27B-7FDB-11D7-A71E-000A957653D6@tercent.net>

On Tue, May 06, 2003 at 12:01:20 -0400,
  Randall Lucas <rlucas@tercent.net> wrote:
> 
> 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?

You can't use a select in a check constraint.
Using a partial index seems to do what you want. Do something like:
create unique index thing_idx on thing (thing_group_id, is_main_thing)
  where is_main_thing = true;

> 
> 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
> 
> 
> ---------------------------(end of broadcast)---------------------------
> TIP 3: if posting/reading through Usenet, please send an appropriate
> subscribe-nomail command to majordomo@postgresql.org so that your
> message can get through to the mailing list cleanly




view thread (7+ messages)  latest in thread

Message-ID: <20030506172354.GA21510@wolff.to>
Permalink:  ../20030506172354.GA21510@wolff.to/
Also on:    postgresql.org/message-id/20030506172354.GA21510@wolff.to

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-sql@postgresql.org
  Cc: bruno@wolff.to, rlucas@tercent.net
  Subject: Re: UNIQUE boolean: only one row may be "true"
  In-Reply-To: <20030506172354.GA21510@wolff.to>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox