MySQL insert on duplicate key; delete?

Spencer Mark picture Spencer Mark · Jul 15, 2012 · Viewed 18.5k times · Source

Is there a way of removing record on duplicate key in MySQL?

Say we have a record in the database with the specific primary key and we try to add another one with the same key - ON DUPLICATE KEY UPDATE would simply update the record, but is there an option to remove record if already exists? It is for simple in/out functionality on click of a button.

Answer

James picture James · Jan 9, 2015

It's a work-around, but it works:

Create a new column and call it do_delete, or whatever, making it a tiny-int. Then do On Duplicate Key Update do_delete = 1;

Depending on your MySQL version/connection, you can execute multiple queries in the same statement. However, if not, just run a separate query immediately afterwords. Either way, the next query would just be: Delete From [table] Where do_delete = 1;. This way, if its a new entry, it will not delete anything. If it was not a new entry, it will then mark it for deletion then you can delete it.