MySQL Double Insertion Prevention

I have a table more or less like

Name | Lastname | ID | Date 

Is there a way to prevent the database from working in the insert function if the person who has such Name , Lastname and ID already exists without running additional queries for it?

+4
source share
1 answer

add a UNIQUE for columns,

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

after it has been implemented, if you try to insert a value that already has an identifier and LastName, it throws 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 
+13
source

All Articles