pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Craig Ringer <craig@postnewspapers.com.au>
To: Robert Edwards <bob@cs.anu.edu.au>
Cc: pgsql-sql@postgresql.org
Subject: Re: uniqueness constraint with NULLs
Date: Mon, 29 Jun 2009 19:32:30 +0800
Message-ID: <1246275150.11346.27.camel@ayaki> (raw)
In-Reply-To: <4A485431.3080707@cs.anu.edu.au>
References: <4A485431.3080707@cs.anu.edu.au>

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




view thread (10+ messages)  latest in thread

Message-ID: <1246275150.11346.27.camel@ayaki>
Permalink:  ../1246275150.11346.27.camel@ayaki/
Also on:    postgresql.org/message-id/1246275150.11346.27.camel@ayaki

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-sql@postgresql.org
  Cc: craig@postnewspapers.com.au, bob@cs.anu.edu.au
  Subject: Re: uniqueness constraint with NULLs
  In-Reply-To: <1246275150.11346.27.camel@ayaki>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox