1

I need to add a constraint to a table x which has many to one relation to other table. So the table x has field other_table_id.

There is other column in table x called primary which is boolean type.

I want to make sure that there is none or only one primary=true per one other_table_id.

Multiple rows can have other_table_id equals some same value and primary=false but only one true per other_table_id.

How do I create this constraint?

1 Answer 1

5

You need a partial unique index for that:

create unique index idx_unique_other 
   on table_x (other_table_id)
   where primary;

This will only index rows where the value of primary column is true. And for those, the other_table_id has to be unique.

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

Comments

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.