1
CREATE TABLE article (
   day integer,
   is_chosen boolean
)
CREATE UNIQUE INDEX day_is_chosen_unique_index ON article (day, is_chosen);

The above will give me an unique index on the two columns, which means on a given day we can have one article that is chosen and one article that is not chosen.

I need to the unique index for the is_chosen field only. In other words, on any given day, we can only have one article that is chosen and multiple articles that are not chosen

Maybe something like this:

CREATE UNIQUE INDEX day_is_chosen_unique_index ON article (day, is_chosen true);

How would I go about creating this composite index?

2
  • "we can have one article that is chosen and one article that is not chosen" Looks more like you can have many days, each of which can be both chosen and not chosen. Commented Feb 21, 2014 at 23:22
  • @samol Did you try the proposed solution? Consider accepting the answer. Commented Aug 23, 2014 at 19:59

1 Answer 1

1

This partial index will suffice:

CREATE TABLE article (
    id          INT
,   when_day    INT
,   is_chosen   BOOLEAN DEFAULT FALSE
);

CREATE UNIQUE INDEX day_is_chosen_unique_index
    ON article ( when_day )
    WHERE is_chosen; 

Note: 'DAY' is reserved keyword in SQL so better not to use it as a column name.

Sign up to request clarification or add additional context in comments.

1 Comment

Here's the documentation for partial indexes: postgresql.org/docs/8.0/static/indexes-partial.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.