i have a problem here. I have a table of the following schema:
id : int(11) not null primary key
name : varchar(255) not null
status : enum('ACTIVE','DELETED')
Note: The records are ‘soft-deleted’ and we just flag the status to ‘DELETED’.
The issue is that i don’t want the a fella to be able to create entry of same name(redundant) via 2 different threads unless the existing record in db is in ‘DELETED’ state. What’s the possible ways to do this?
I cant just unique index the name + status, because if we have an item(with same name) in ‘DELETED’, and my want-to-be-deleted zone is ‘ACTIVE’, error will happened as i flag the zone to be ‘DELETED’.
How about adding a deleted_at field with your data? Then you can have a unique key on name + status + deleted_at. When status = ACTIVE, there can only be one value for deleted_at, so that will make the uniqueness be on name only.
EDIT for clarity:
EDIT #2: actually, if you make your “check if deleted” code check for deleted_at > 0 instead of checking for status=deleted, then you don’t even need the status field.