Solid
Solid

Reputation: 63

mysql prevent redundant records with multiple fields

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'.

Upvotes: 2

Views: 181

Answers (2)

ziad-saab
ziad-saab

Reputation: 20269

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:

CREATE TABLE mytable (
  id int not null primary key,
  name varchar(255) not null,
  status enum('active','delete'),
  deleted_at datetime not null default 0,
  UNIQUE KEY one_active (name, status, deleted_at)
);

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.

Upvotes: 3

Roman Newaza
Roman Newaza

Reputation: 11700

You should achieve your goal programmatically. Check with your language if name + status ACTIVE exists to restrict INSERT.

Upvotes: 0

Related Questions