How to guarantee uniqueness of field's value?

I have a table looking like this:

id      bigint,
user_id bigint,
main    boolean,
...

Of all entries with same user_id only one can have main = true. Please, advice, how to realize it?

Upvotes: 0

Views: 45

Answers (1)

Jeremy
Jeremy

Reputation: 6723

You can use a partial index.

CREATE UNIQUE INDEX index_name ON table_name (user_id) WHERE main;

Upvotes: 3

Related Questions