Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql insert after delete fails because of "duplicate entry"

Tags:

sql

mysql

I have a code with two mysql queries.
DELETE FROM my_table WHERE user_id=some_number
INSERT INTO my_table (user_id, ... ) VALUES(some_number, ...)

The field user_id is unique.

In rare cases the insert fails claiming a duplicate entry occurred. My first instinct leads me to to believe the DELETE didn't finish and now the insert is trying to insert and I'm getting a duplicate entry. Is this possible? How can I avoid this? Might there be a different explanation you can think of?

Update: The reason I'm deleting is because I want to delete all the data that I am not updating / inserting for the first time. Also, I think it is important to state that most of the data remains the same.

like image 827
Noam Avatar asked Jul 21 '11 14:07

Noam


People also ask

How do I ignore duplicates in MySQL?

Use the INSERT IGNORE command rather than the INSERT command. If a record doesn't duplicate an existing record, then MySQL inserts it as usual. If the record is a duplicate, then the IGNORE keyword tells MySQL to discard it silently without generating an error.

Why delete is not working in MySQL?

Solution. By default, MySQL workbench is started in safe mode, and can't update or delete, without a “WHERE” condition, see the error message. To fix it, in menu, selects “Edit” -> “Preferences” -> “SQL Queries”, uncheck the “Safe Updates” checkbox. Done, try reconnect and issue the delete command again.

How do I use insert ignore?

However, if you use the INSERT IGNORE statement, the rows with invalid data that cause the error are ignored and the rows with valid data are inserted into the table. The syntax of the INSERT IGNORE statement is as follows: INSERT IGNORE INTO table(column_list) VALUES( value_list), ( value_list), ...

Is deletion and insertion possible in MySQL?

Using DELETE to remove rows from tablesThe SQL DELETE command is used to remove rows from tables, functioning as the complementary action to INSERT . In order to remove rows from a table, you must identify the rows you wish to target by providing match criteria within a WHERE clause.


2 Answers

SET AUTOCOMMIT=0;    
START TRANSACTION;    
DELETE FROM my_table WHERE user_id=some_number;     
INSERT INTO my_table (user_id, ... ) VALUES(some_number, ...); 
commit;
like image 160
Fam Khan Avatar answered Sep 20 '22 08:09

Fam Khan


Use an UPDATE statement instead:

UPDATE my_table
SET my_column = my_value
WHERE user_id = some_number
like image 40
Trey Copeland Avatar answered Sep 18 '22 08:09

Trey Copeland