Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to No-op if a duplicate key exception occurs?

Tags:

sql

mysql

I know I can use the ON DUPLICATE KEY UPDATE and then do a no-op operation in MySQL if a duplication exception occurs, but is there a more efficient way?

like image 357
stevebot Avatar asked Sep 20 '25 00:09

stevebot


2 Answers

While that is true, I've found that doing INSERT IGNORE creates holes in your auto increment ids. Specifically, if you do an INSERT IGNORE and it collides with a current row, no data is written (what you want), BUT the auto_increment value for that table gets incremented by one.

If you're narcotic like me, holes in auto increment columns kill you. So I tend to not do that. I just do something like:

INSERT INTO TABLE (column list) VALUES (value list) ON DUPLICATE KEY UPDATE random_column = random_column

This successfully does a no-op. It's purely a matter of style, but I think this method is cleaner.

like image 53
Landon Avatar answered Sep 21 '25 14:09

Landon


INSERT IGNORE INTO tableName ....

see the Docs

like image 38
The Scrum Meister Avatar answered Sep 21 '25 14:09

The Scrum Meister