Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - ignore insert error: duplicate entry

Tags:

php

mysql

insert

I am working in PHP.

Please what's the proper way of inserting new records into the DB, which has unique field. I am inserting lot of records in a batch and I just want the new ones to be inserted and I don't want any error for the duplicate entry.

Is there only way to first make a SELECT and to see if the entry is already there before the INSERT - and to INSERT only when SELECT returns no records? I hope not.

I would like to somehow tell MySQL to ignore these inserts without any error.

Thank you

like image 889
neon Avatar asked May 01 '09 17:05

neon


People also ask

How can we avoid inserting duplicate records in MySQL using node JS?

How it is possible ? - Check for fields that You send to API with records in user table. Make sure they're not exist. For more detailed information to client-side app I recommend to check database table for record existence before doing insert.


1 Answers

You can use INSERT... IGNORE syntax if you want to take no action when there's a duplicate record.

You can use REPLACE INTO syntax if you want to overwrite an old record with a new one with the same key.

Or, you can use INSERT... ON DUPLICATE KEY UPDATE syntax if you want to perform an update to the record instead when you encounter a duplicate.

Edit: Thought I'd add some examples.

Examples

Say you have a table named tbl with two columns, id and value. There is one entry, id=1 and value=1. If you run the following statements:

REPLACE INTO tbl VALUES(1,50); 

You still have one record, with id=1 value=50. Note that the whole record was DELETED first however, and then re-inserted. Then:

INSERT IGNORE INTO tbl VALUES (1,10); 

The operation executes successfully, but nothing is inserted. You still have id=1 and value=50. Finally:

INSERT INTO tbl VALUES (1,200) ON DUPLICATE KEY UPDATE value=200; 

You now have a single record with id=1 and value=200.

like image 83
zombat Avatar answered Sep 30 '22 07:09

zombat