0

I have a card table where I need to have a constraint, when a user has a card in ACTIVE or LOCKED state a new card shouldn't be created.

CREATE TABLE card
(cardId int,
userId int,
cardState varchar(255)); 

I tried exploring exclusion using gist exclusion and partial unique index but couldn't make any progress. Any help would be appreciated.

2
  • 1
    I think you should use trigger for that purpose. Commented Nov 21, 2022 at 19:37
  • 2
    @BartoszOlchowik: No need for, too complex for such a simple thing as a conditional unique constraint Commented Nov 21, 2022 at 19:49

1 Answer 1

3

Use a conditional unique constraint/index:

CREATE TABLE card
(cardId int,
userId int,
cardState varchar(255)); 

CREATE UNIQUE INDEX u_user_id_card_state ON card(userId) WHERE cardState IN('ACTIVE','LOCKED');

INSERT INTO card(cardid, userid, cardstate) VALUES(1,1, 'ACTIVE');

INSERT INTO card(cardid, userid, cardstate) VALUES(1,1, 'ACTIVE'); -- fails

INSERT INTO card(cardid, userid, cardstate) VALUES(1,1, 'LOCKED'); -- fails

INSERT INTO card(cardid, userid, cardstate) VALUES(1,1, 'something else'); -- works
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it worked! I was making the index on combination of userId and state. CREATE UNIQUE INDEX u_user_id_card_state ON card(userId) WHERE cardState IN('ACTIVE','LOCKED'); which is why it didn't work.

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.