Re: Multi-Column Constraints and Null Values

From: "Tornroth, Phill" <ptornroth(at)intellidot(dot)net>
To: "Tom Lane" <tgl(at)sss(dot)pgh(dot)pa(dot)us>, "Bruno Wolff III" <bruno(at)wolff(dot)to>
Cc: "Jeff Frost" <jeff(at)frostconsultingllc(dot)com>, <pgsql-sql(at)postgresql(dot)org>
Subject: Re: Multi-Column Constraints and Null Values
Date: 2006-04-30 02:48:34
Message-ID: 967F41F63A2D10469114F0A19E56B17E365D4A@SIRIUS.intellidot.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Wow. This is great feedback. As for more than two columns.. I don't think I have more than two nullable columns. Often I have a three or four column constraint where only one or two of them are nullable. I've never used constraints or indexes with where clauses. I'll have to play with this a bit to understand how it works. Thanks for the tips!

Phill

-----Original Message-----
From: Tom Lane [mailto:tgl(at)sss(dot)pgh(dot)pa(dot)us]
Sent: Sat 4/29/2006 3:02 PM
To: Bruno Wolff III
Cc: Jeff Frost; Tornroth, Phill; pgsql-sql(at)postgresql(dot)org
Subject: Re: [SQL] Multi-Column Constraints and Null Values

Bruno Wolff III <bruno(at)wolff(dot)to> writes:
> To block multiple entries where one of the columns is null he needs to
> add extra checks. One way to do this is to add a partial index for each column
> with the condition that the other column IS NULL. This will cover everything
> but the case where both columns are null. If this case isn't allowed, then
> a row constraint can be used to block it. If it is allowed, the only thing that
> comes to mind is making an SQL function that counts the number of rows where
> both columns are null and calling that function in a row constraint and
> checking that the result is <= 1.

Nah, it's easy:

CREATE UNIQUE INDEX fooi ON foo ((0))
WHERE col1 IS NULL AND col2 IS NULL;

So you'd need a total of four unique indexes (3 of 'em partial) to
enforce the condition for two columns. The real problem with this
is that it doesn't scale well for more than two columns :-(

regards, tom lane

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Ben K. 2006-05-01 01:29:26 Re: Linked List
Previous Message Tom Lane 2006-04-29 22:02:41 Re: Multi-Column Constraints and Null Values