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

Поиск
Список
Период
Сортировка
От Thomas Kellerer
Тема Re: Way to create unique constraint in Postgres even with null columns
Дата
Msg-id jaub4g$rte$1@dough.gmane.org
обсуждение исходный текст
Ответ на Way to create unique constraint in Postgres even with null columns  (Mike Christensen <mike@kitchenpc.com>)
Ответы Re: Way to create unique constraint in Postgres even with null columns  (Mike Christensen <mike@kitchenpc.com>)
Список pgsql-general
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;




В списке pgsql-general по дате отправления:

Предыдущее
От: Pavel Stehule
Дата:
Сообщение: Re: Way to create unique constraint in Postgres even with null columns
Следующее
От: Mike Christensen
Дата:
Сообщение: Re: Way to create unique constraint in Postgres even with null columns