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.