So this morning I was boggling on a data migration with Magento that kept throwing the following MySQL error:
1 |
[ERROR in query 5] Duplicate entry '1' for key 'PRIMARY' |
This was really puzzling me, since all I did was I created a database dump and tried to import it on another server. So what was going on? Well… It turns out that Magento uses a primary key with value “0” in some cases (which is bad practice). MySQL’s default behaviour when inserting data in auto incremental fields with value “0” is to set it to the next possible auto increment value. Which – for an empty table – is “1”.
The query
So… if you have the following query:
1 2 3 4 5 6 7 |
INSERT INTO `core_store` (`store_id`, `code`, `website_id`, `group_id`, `name`, `sort_order`, `is_active`) VALUES (0,'admin',0,0,'Admin',0,1), (1,'store1',1,1,'Store 1',0,1), (2,'store2',2,2,'Store 2',10,1), (3,'store3',3,3,'Store 3',0,1), (4,'store4',3,4,'Store 4',0,1); |
MySQL will set the store_id of line 1 to “1” instead of “0”, causing the importing of line 2 to fail, because there already exists a row where store_id = 1. Oh you Magento…
The fix
The fix is utterly simple. It’s a typical example where hours of work, stress and debugging result in a one-liner that fixes it all. Make sure in your SQL-dump file to add the following line at the top:
1 |
SET sql_mode='NO_AUTO_VALUE_ON_ZERO'; |
The key here is NO_AUTO_VALUE_ON_ZERO : this tells MySQL to not set the value to the value that the auto incrementer proposes, but just set the value to “0”. And that’s it! It really is that simple…
You can also make it more permanent by editing your my.cnf -file and add the following rule to the [mysqld] -section:
1 |
sql_mode=NO_AUTO_VALUE_ON_ZERO |
You can also create a custom configuration file, just for this rule by creating a file called /etc/mysql/conf.d/sql_mode.cnf and adding the following lines in it:
1 2 |
[mysqld] sql_mode=NO_AUTO_VALUE_ON_ZERO |
Visitors give this article an average rating of 3.6 out of 5.
How would you rate this article?
★ ★ ★ ★ ★
Hello Giel, thank you VERY MUCH for posting this – made my day :). Jörg
Hello Giel,
I’m trying to run a file in MySQL of my Magento store.
I have a issue: “Duplicate entry ‘1’ for key ‘PRIMARY’.” Even adding “SET sql_mode = ‘NO_AUTO_VALUE_ON_ZERO’;”, the error continues.
Can you help me?
Thanks 🙂
Thank you for sharing this! Saved me a few hours.
made my day ! Thanks!