Re: unique constraint with significant nulls? - Mailing list pgsql-general

From Andreas Joseph Krogh
Subject Re: unique constraint with significant nulls?
Date
Msg-id 5061EBE2.6030707@officenet.no
Whole thread Raw
In response to unique constraint with significant nulls?  (Mike Blackwell <mike.blackwell@rrd.com>)
Responses Re: unique constraint with significant nulls?
List pgsql-general
On 09/25/2012 05:05 PM, Mike Blackwell wrote:
> How would one go about building a multi-column unique constraint where
> null is a significant value, eg. (1, NULL) <> (2, NULL)?
>
> I see a number of references to not being able to use an index for
> this, but no mention of an alternative.  Any pointers would be appreciated

create table my_table(
some_column varchar not null,
other_column varchar);

create unique index my_idx on my_table(some_column, other_column) where
other_column is not null;
create unique index my_fish_idx on my_table(some_column) where
other_column is null;

insert into my_table (some_column, other_column) values('a', 'a');
insert into my_table (some_column, other_column) values('a', 'b');
insert into my_table (some_column) values('a');
insert into my_table (some_column) values('b');

-- fails
insert into my_table (some_column, other_column) values('a', 'a');
-- also fails
insert into my_table (some_column) values('a');

result:

andreak=# insert into my_table (some_column, other_column) values('a', 'a');
ERROR:  duplicate key value violates unique constraint "my_idx"
DETAIL:  Key (some_column, other_column)=(a, a) already exists.

andreak=# insert into my_table (some_column) values('a');
ERROR:  duplicate key value violates unique constraint "my_fish_idx"
DETAIL:  Key (some_column)=(a) already exists.


--
Andreas Joseph Krogh<andreak@officenet.no>  - mob: +47 909 56 963
Senior Software Developer / CEO - OfficeNet AS - http://www.officenet.no
Public key: http://home.officenet.no/~andreak/public_key.asc



pgsql-general by date:

Previous
From: Misa Simic
Date:
Subject: Re: pljava and Postgres 9.2.1
Next
From: "W. Matthew Wilson"
Date:
Subject: Rank based on the number of matching OR fields?