When to insert on duplicate update in MySQL?

When to insert on duplicate update in MySQL?

If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, MySQL performs an UPDATE of the old row.

What happens when you insert a duplicate in a record?

You insert a supposedly new record, with a new PRIMARY key value (say a UUID), but you happen to have a duplicate value for its UNIQUE key. What you want is a proper exception, indicating that you are trying to insert a duplicate into a UNIQUE column.

When to insert a primary key in MySQL?

Insert if the PRIMARY key value does not exist (inserts 1 or 0 rows). Only one of these queries will have an effect. The UPDATE is easy. As for the INSERT: WHERE id = 1 results in a row if the id exists, or no row if it does not.

What can go horribly wrong with on duplicate update?

And most people get it wrong, due to what MySQL offers. The requirement: Insert unless the PRIMARY key exists, otherwise update. The result of that approach, disturbingly: Insert unless the PRIMARY or any UNIQUE key exists, otherwise update! What can go horribly wrong with ON DUPLICATE KEY UPDATE?

How to update record ID with duplicate key?

If you need to check and update according to record id, you have to provide the KEY as well, which in your case is id. Now if, the id is duplicate, the row will update. In phpmyadmin go to the structure. Down in inexes click on go. index name set the same name like column for UNIQUE value.

Is there way to replace duplicate key in MySQL?

You may want to consider using REPLACE INTO syntax, but be warned, upon duplicate PRIMARY / UNIQUE key, it DELETES the row and INSERTS a new one. You won’t need to re-specify all the fields.

How to insert a duplicate key into a database?

Let I have 2 tables in database: (1) brand (2) brand_item. Javascript code to insert into brand table : ON DUPLICATE KEY UPDATE is taken care of in INSERT query.