Re: Way to create unique constraint in Postgres even with null columns

From: Mike Christensen <mike(at)kitchenpc(dot)com>
To: Thomas Kellerer <spam_eater(at)gmx(dot)net>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Way to create unique constraint in Postgres even with null columns
Date: 2011-11-27 22:02:23
Message-ID: CABs1bs2DxPKzWJPBD=L5NORsEt9mCN2+mDFaXR1YFxLDjSb4Nw@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Sun, Nov 27, 2011 at 1:47 PM, Thomas Kellerer <spam_eater(at)gmx(dot)net> wrote:
> Mike Christensen wrote on 27.11.2011 22:18:
>>
>> I have a table with this layout:
>>
>>     CREATE TABLE Favorites
>>     (
>>       FavoriteId uuid NOT NULL, --Primary key
>>       UserId uuid NOT NULL,
>>       RecipeId uuid NOT NULL,
>>       MenuId uuid
>>     )
>>
>> I want to create a unique constraint similar to this:
>>
>>     ALTER TABLE Favorites ADD CONSTRAINT Favorites_UniqueFavorite
>> UNIQUE(UserId, MenuId, RecipeId);
>>
>> However, this will allow multiple rows with the same UserId and
>> RecipeId, if the MenuId is null.  I want to allow a NULL MenuId to
>> store a favorite that has no associated menu, but I only want at most
>> one of these rows per user/recipe pair.
>
> In addition to the above unique constraint you will need another one:
>
> CREATE UNIQUE INDEX Favorites_UniqueFavorite
>   ON (UserId, MenuId)
>   WHERE RecipeId IS NULL;

Excellent solution! Thanks all..

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message David Johnston 2011-11-27 22:18:22 Re: Way to create unique constraint in Postgres even with null columns
Previous Message Thomas Kellerer 2011-11-27 21:47:48 Re: Way to create unique constraint in Postgres even with null columns