Unique PostgreSQL index for a set of specific values
source link: https://www.codesd.com/item/unique-postgresql-index-for-a-set-of-specific-values.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Unique PostgreSQL index for a set of specific values
Let's say there is a table AVATARS and among other columns it has user_id
(foreign key to users table) and state
where state can be any value from 0 to 6. I want to create a constraint so that user can have only 2 avatars, where one has state = 0 and the other has any state != 0. I wonder if it's possible to implement with a unique index? Or I am gonna have to add some boolean column?
You could use a unique index with an expression:
CREATE UNIQUE INDEX avatars_userid_state_0_idx ON avatars(user_id,(state<>0));
(or state = 0
, the end result is the same).
Related Articles
Is it possible to have a unique mysql index for a specific column value?
What is the best performing table index for a set of history records?
Oracle: unique index with verification of a specific value
How to search for a set of specific pattern strings using a regular expression?
Update the Magento index for one or more specific products
How do I get COUNT from a column on a set of specific values from multiple columns?
If the input field is blank, set a specific value
How to query a C # dictionary and return a set of specific values
The PostgreSQL query for a list of allowed values in a constraint?
A Spec Clojure for a set with false values in them
Unable to set a specific value in a list menu
Sumifs, but only once for each set of corresponding values
Set a specific value to select an entry on jQuery return false?
Do I need one or two exclusive key indexes for this table?
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK