Re: uniqueness constraint with NULLs

From: "A(dot) Kretschmer" <andreas(dot)kretschmer(at)schollglas(dot)com>
To: pgsql-sql(at)postgresql(dot)org
Subject: Re: uniqueness constraint with NULLs
Date: 2009-06-29 08:20:58
Message-ID: 20090629082058.GG24737@a-kretschmer.de
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

In response to Leo Mannhart :
> On Mon, 2009-06-29 at 17:08 +1000, Robert Edwards wrote:
> > A. Kretschmer wrote:
> > > In response to Robert Edwards :
> > >> Can anyone suggest a way that I can impose uniqueness on a and b when
> > >> c is NULL?
> > >
> > > Sure, use a functional index:
> > >
> > > test=# create table bobtest (a int, b int, c int);
> > > CREATE TABLE
> > > test=*# create unique index idx_bobtest on
> > > bobtest(a,b,coalesce(c::text,'NULL'));
> > > CREATE INDEX
> > > test=*# insert into bobtest (a, b) values (1, 4);
> > > INSERT 0 1
> > > test=*# insert into bobtest (a, b, c) values (1, 4, NULL);
> > > ERROR: duplicate key value violates unique constraint "idx_bobtest"
> > > test=!#
> > >
> Why changing the datatype of coulumn "c"? Will this not probably disable
> the use of the index? Why not only:

Maybe, depends on the query.

>
> lem=# create table bobtest (a int, b int, c int);
> CREATE TABLE
> lem=# create unique index idc_bobtest on bobtest (a, b, coalesce(c, 1));

bad idea if 1 is a valid value for this column.

Andreas
--
Andreas Kretschmer
Kontakt: Heynitz: 035242/47150, D1: 0160/7141639 (mehr: -> Header)
GnuPG-ID: 0x3FFF606C, privat 0x7F4584DA http://wwwkeys.de.pgp.net

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Mario Splivalo 2009-06-29 08:47:16 date_trunc should be called date_round?
Previous Message A. Kretschmer 2009-06-29 08:02:32 Re: uniqueness constraint with NULLs