0

I want to protect the integrity of a state machine with a partial unique index. For a given listing_id, there should not be more than one record with status < 3.

In other words, this is ok:

listing_id, array_agg(status)
1234, {0,3,3}

But this is not:

listing_id, array_agg(status)
1234, {0,1,3}

My first thought was something like this:

CREATE UNIQUE INDEX
  uq_state_machine_protection_per_listing_id
  ON listing_version(listing_id, status)
  WHERE status in (0,1,2);

But that's not good enough-- it only prevents multiple records with the same value of less than 3. My negative case example above would still pass the constraint.

1 Answer 1

1

It can be dealt with by creating an index on constant. How about:

CREATE UNIQUE INDEX
  uq_state_machine_protection_per_listing_id
  ON listing_version(listing_id)
  WHERE status in (0,1,2);
Sign up to request clarification or add additional context in comments.

1 Comment

@kelorek Well, if you're including listing_id you don't need the other column.

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.