Re: UNIQUE columnt depdening on other column???

From: Reinoud van Leeuwen <reinoud(dot)v(at)n(dot)leeuwen(dot)net>
To: pgsql-sql(at)postgresql(dot)org
Subject: Re: UNIQUE columnt depdening on other column???
Date: 2004-06-02 12:43:45
Message-ID: 20040602124345.GQ23232@spoetnik.xs4all.nl
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Wed, Jun 02, 2004 at 02:39:45PM +0300, Andrei Bintintan wrote:
> Hi,
>
> I have a problem.
>
> Let's say I have the following table:
> CREATE TABLE rekl_element(
> id serial PRIMARY KEY,
> active boolean NOT NULL DEFAULT 'y',
> num int4 NOT NULL,
> text varchar(10)
> );
>
> Now I want that "num" column is "unique" but only for those columns that
> have active='y'. For the columns that have active='f' I don't care if num is
> unique or not. I'm asking this because num will be doubled some times.

You can use a little trick for this.
Add a column 'uniqueness' that has a default nextval ('mysequence'::text).
Make an unique index on the columns (num, uniqueness).
Obviously, this will work because the column uniqueness has unique values.

Now write a trigger that sets the uniqueness column to 0 when the active
column equals 'y'. This will result in:

- unique num columns (or the index will fail) where active = 'y'
- arbitrary num colums (index will always be unique) where active = 'n'


--
__________________________________________________
"Nothing is as subjective as reality"
Reinoud van Leeuwen reinoud(dot)v(at)n(dot)leeuwen(dot)net
http://www.xs4all.nl/~reinoud
__________________________________________________

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Rajesh Kumar Mallah 2004-06-02 13:48:17 Re: assistance on self join pls
Previous Message Richard Huxton 2004-06-02 12:21:53 Re: UNIQUE columnt depdening on other column???