Re: uniqueness constraint with NULLs

From: Craig Ringer <craig(at)postnewspapers(dot)com(dot)au>
To: Robert Edwards <bob(at)cs(dot)anu(dot)edu(dot)au>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: uniqueness constraint with NULLs
Date: 2009-06-29 11:32:30
Message-ID: 1246275150.11346.27.camel@ayaki
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Mon, 2009-06-29 at 15:42 +1000, Robert Edwards wrote:

> Can anyone suggest a way that I can impose uniqueness on a and b when
> c is NULL?

One way is to add an additional partial index on (a,b):

CREATE INDEX bobtest_ab_unique ON bobtest(a,b) WHERE (c IS NULL);

... however, if you want to do the same sort of thing for all
permutations (a, null, null), (b, null, null), (c, null, null), (a, b,
null), (a, c, null), (b, c, null), (a, b, c)that'll be a LOT of indexes.

In that case you might be better off just using a trigger function like
(untested but should be about right):

CREATE OR REPLACE FUNCTION bobtest_unique_trigger() RETURNS trigger AS
$$
declare
conflicting_id integer;
begin
if TG_OP = 'INSERT' or TG_OP = 'UPDATE' then
select into conflicting_id from bobtest
where (NOT new.a IS DISTINCT FROM a)
and (NOT new.b IS DISTINCT FROM b)
and (NOT new.c IS DISTINCT FROM c);
if found then
raise exception 'Unique violation in bobest: inserted row
conflicts with row id=%',conflicting_id;
end if;
end if;
end;
$$ LANGUAGE 'plpgsql';

... which enforces uniqueness considering nulls.

> In the real app., c is a date field and I require it to be NULL for
> some rows.

Oh. Er, In that case, the partial unique index is your best bet (but 'a'
and 'b' should ne NOT NULL, right).

> in case I am missing some other solution that
> doesn't involve the use of triggers etc.

Sometimes a trigger is the right solution.

--
Craig Ringer

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Tom Lane 2009-06-29 14:01:23 Re: uniqueness constraint with NULLs
Previous Message Mario Splivalo 2009-06-29 08:47:16 date_trunc should be called date_round?