Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 760
user2228063 Avatar asked Dec 12 '22 16:12

user2228063


1 Answers

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
like image 193
John Woo Avatar answered Dec 21 '22 09:12

John Woo