Received: from maia.hub.org (unknown [200.46.204.183]) by mail.postgresql.org (Postfix) with ESMTP id DC2B3633C7B for ; Mon, 29 Jun 2009 11:01:34 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.183]) (amavisd-maia, port 10024) with ESMTP id 79227-09 for ; Mon, 29 Jun 2009 11:01:33 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from sss.pgh.pa.us (sss.pgh.pa.us [66.207.139.130]) by mail.postgresql.org (Postfix) with ESMTP id 9155463396E for ; Mon, 29 Jun 2009 11:01:33 -0300 (ADT) Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.14.2/8.14.2) with ESMTP id n5TE1Nmm011274; Mon, 29 Jun 2009 10:01:23 -0400 (EDT) To: Craig Ringer cc: Robert Edwards , pgsql-sql@postgresql.org Subject: Re: uniqueness constraint with NULLs In-reply-to: <1246275150.11346.27.camel@ayaki> References: <4A485431.3080707@cs.anu.edu.au> <1246275150.11346.27.camel@ayaki> Comments: In-reply-to Craig Ringer message dated "Mon, 29 Jun 2009 19:32:30 +0800" Date: Mon, 29 Jun 2009 10:01:23 -0400 Message-ID: <11273.1246284083@sss.pgh.pa.us> From: Tom Lane X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=0 tagged_above=0 required=5 tests=none X-Spam-Level: X-Archive-Number: 200906/121 X-Sequence-Number: 32726 Craig Ringer writes: > 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); That's the way I'd suggest; unlike the other proposal, it doesn't make any assumptions about datatypes and it doesn't require there to be a special non-null value that won't be a real data value. > ... 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. ... yeah. So one answer that definitely requires consideration is "you have misdesigned your data representation; do not try to use NULL this way". > In that case you might be better off just using a trigger function like > (untested but should be about right): This trigger has race conditions: it will fail to prevent concurrent insertion of rows that you would like to have conflict. I think it does the wrong thing for the UPDATE case too, though that is fixable. The race condition isn't. regards, tom lane