user2228063
user2228063

Reputation: 241

Preventing MySQL double insert

I have a table more or less looking like

Name | Lastname | ID | Date 

Is there a way to prevent the database from running the insert function if a person which such Name, Lastname and ID already exists without running additional queries searching for him?

Upvotes: 4

Views: 1286

Answers (1)

John Woo
John Woo

Reputation: 263733

add a UNIQUE constraint on the columns,

ALTER TABLE TableName ADD CONSTRAINT tb_uq UNIQUE (ID, LastName)

once it has been implemented, if you try to insert a value which ID and LastName already existed, it will throw an exception. example

INSERT INTO tableName (ID, LASTNAME) VALUES (1, 'hello') // ok
INSERT INTO tableName (ID, LASTNAME) VALUES (2, 'hello') // ok
INSERT INTO tableName (ID, LASTNAME) VALUES (1, 'hello') // failed

Upvotes: 13

Related Questions