5

I currently have the following constraint on a table:

ALTER TABLE myTable
 ADD CONSTRAINT unique_row UNIQUE (content_id, brand_id, language_id);

I want to add a condition to the constraint: I want the constraint to work the same way, but with only a single row where is_archived is FALSE:

ALTER TABLE myTable
 ADD CONSTRAINT unique_row UNIQUE (content_id, brand_id, language_id, !is_archived);

However, when I do this I get a syntax error.

If is_archived = true then multiple rows with the same combination of content_id and brand_id are allowed. Basically multiple rows that are the same can be archived, but only one can be unarchived.

Hannah Vernon
71.1k22 gold badges178 silver badges324 bronze badges
asked Dec 4, 2020 at 17:39
1

1 Answer 1

9

While Postgres doesn't allow a partially unique constraint, it does support a partial unique index:

create unique index unique_row on myTable(content_id, brand_id) where not is_archived;

See Partial Indexes in the Postgres documentation.

This is effectively pretty much the same as a unique constraint, because such constraints are implemented with unique indexes anyway.

Laurenz Albe
62.1k4 gold badges57 silver badges93 bronze badges
answered Dec 4, 2020 at 17:59
2
  • Index lacks an option to be mentioned in ON CONFLICT case where only unique keys are accepted. Commented May 19, 2022 at 18:54
  • 3
    @AlexDvoretsky You can! You have to specify the same where that the partial index has after the columns in the on conflict clause. eg ... on conflict(content_id, brand_id) where not is_archived do update ... Commented May 19, 2022 at 18:59

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.