Re: Check/unique constraint question

From: Michael Glaesemann <grzm(at)myrealbox(dot)com>
To: Jeff Frost <jeff(at)frostconsultingllc(dot)com>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: Check/unique constraint question
Date: 2006-03-05 11:50:28
Message-ID: D9530855-D63F-4887-96E9-8D90BB7C9996@myrealbox.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql


On Mar 5, 2006, at 17:25 , Jeff Frost wrote:

> And would like to make a unique constraint which would only check
> the uniqueness of id if active=true.

I believe you're looking for what is called a partial index.

http://www.postgresql.org/docs/current/interactive/indexes-partial.html

Note, I've added a foo_id column to make sure each row is unique.
(Duplicates are a Bad Thing.)

create table foo
(
foo_id serial not null
, id integer not null
, active boolean not null

);

create unique index foo_partial_idx on foo (id) where active;

insert into foo (id, active) values (5, false);
insert into foo (id, active) values (5, false);
insert into foo (id, active) values (5, true);
insert into foo (id, active) values (6, false);
insert into foo (id, active) values (6, true);

select * from foo;

foo_id | id | active
--------+----+--------
1 | 5 | f
2 | 5 | f
3 | 5 | t
4 | 6 | f
5 | 6 | t
(5 rows)

insert into foo (id, active) values (5, true);
ERROR: duplicate key violates unique constraint "foo_partial_idx"

Michael Glaesemann
grzm myrealbox com

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message sramsay 2006-03-05 15:16:52 functions in WHERE clause
Previous Message Karsten Hilbert 2006-03-05 10:29:42 Re: Check/unique constraint question