Magento 2 Integrity Constraint Violation Issues & Solutions

In the following article, you will find the most common Magento 2 integrity constraint violation issues described. Below, we combine answers from different platforms to cover as many examples as necessary for keeping this material epistemic and clear. You can find more tips in this article: Magento 2 Cookbook.
 
                
			
			What is the root of all evil when it comes to Magento 2 integrity constraint violations? Duplicate entries are a reason for numerous issues caused by integrity constraint violations in Magento 2. Below, we provide several examples of how to discover and fix them. Although the described situations may look similar at first glimpse, they have slightly different solutions. Let’s start our exploration of integrity constraint violation in Magento 2 from the upgrade to newer versions.
Table of contents
- 1 Integrity constraint violation on setup:upgrade
- 2 Integrity constraint violation when upgrading Magento 2
- 3 Integrity constraint violation during Magento 2 cron setup
- 4 Integrity constraint violation during Magento 2 migration
- 5 The impact of MySQL foreign_key_checks on the entire database
- 6 How to disable a MySQL foreign key constraint temporarily
Integrity constraint violation on setup:upgrade
shares the following Magento 2 integrity constraint violation issue. After updating to 2.3.3, the author gets an error related to the Temando_Shipping module. To solve the problem, AntondeG disabled the module. Unfortunately, this solution caused another problem – errors while editing products. An attempt to rerun the magento setup:upgrade command leads to the following integrity constraint violation issue:
| 1 | Upgrading data.. SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'origin.address.countryCode' for key 'PRIMARY', query was: INSERT INTO `temando_product_attribute_mapping` (`node_path_id`,`label`,`description`,`mapping_attribute_id`,`is_default`) | 
So, what was the solution? According to , there is an efficient workaround. However, it is not a serious solution. The author thinks that it is a bug in temando/module-shipping-m2 required by magento/product-community-edition. Since the data is added in vendor/temando/module-shipping-m2/Setup/UpgradeData.php:73, kolaente proposes to check the difference between the content in the database and the data inserted during the module upgrade. The author provides the following command to do that:
| 1 | select * from temando_product_attribute_mapping; | 
If the data is identical, it is necessary to delete it. Use this command:
| 1 | delete from temando_product_attribute_mapping; | 
After that, it is possible to rerun the bin/magento setup:upgrade command.
Follow this link for further information: .
Integrity constraint violation when upgrading Magento 2
This case describes an issue that occurs during the Magento upgrade from 2.1.x to 2.2.x. The corresponding error looks as follows:
| 1 2 3 4 | Module 'Magento_SalesRule': Upgrading data.. SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry'0-0-0-0' for key 'PRIMARY', query was: INSERT INTO `salesrule_product_attribute` () VALUES () | 
The author proposes two solutions to fix this Magento 2 integrity constraint violation problem
I
First of all, you have to visit the following location and modify the Rule.php file with the empty data condition.
| 1 2 | vendor/magento/module-sales-rule/Model/ResourceModel/Rule.php line 352 $connection->insertMultiple($this->getTable('salesrule_product_attribute'), $data); | 
The author of the solution recommends to wrap it in
| 1 2 3 | if (!empty($data)) {     $connection->insertMultiple($this->getTable('salesrule_product_attribute'), $data); } | 
Now, it is necessary to run this command via SSH in the root of your Magento installation:
| 1 | php bin/magento setup:upgrade | 
That’s it. Let’s take a look at the second solution.
II
Before going any further, you have to create a backup of the database and tables you will work with. The current solution deletes all data related to sales rules and coupons. Run the following Query in PhpMyAdmin to truncate tables:
| 1 2 3 4 5 | TRUNCATE TABLE salesrule; TRUNCATE TABLE salesrule_coupon; TRUNCATE TABLE salesrule_coupon_usage; TRUNCATE TABLE salesrule_customer; TRUNCATE TABLE salesrule_product_attribute; | 
Now, you can run php bin/magento setup:upgrade via SSH in the Magento installation root. For further information, hit this link: .
Integrity constraint violation during Magento 2 cron setup
user reports about an integrity constraint violation when setting up cron for Magento 2.2.2. However, nothing seems to be updating. The author of the discussion provides the following error message:
| 1 2 | SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '4639-168-1-283-4639' for key 'PRIMARY', query was: INSERT INTO    `catalog_product_index_eav_temp` (`entity_id`,`attribute_id`,`store_id`,`value`,`source_id`) VALUES () | 
proposes a solution. The author of the answer describes the entry key from the error message, pointing to the cause of the issue:
- 4639 – product_id
- 168 – attribute_id
- 1 – store_id
- 283 – attribute_value_id
Next, dev_67Commerce supposes that the attribute type of 168 is varchar and concludes that its values are available in catalog_product_entity_varchar.
Now, it is necessary to search for attribute 168 along with entity_id 4639. This step reveals the content of the ‘value‘ column. As a result, you can remove all duplicate values: the issue is caused by the same comma-separated values of value_id 283 (from the error above).
After you’ve fixed the content of the table, save your work, flush cache, and re-run the index command. Repeat the above actions if similar integrity constraint violations for other products take place. You can see more details here: .
Integrity constraint violation during Magento 2 migration
There is another approach to the issue we’ve just described. This time, the problem occurs while running the data migration tool. The author of the material constantly came across the following error message.
| 1 | SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry ‘611516’ for key ‘PRIMARY’. | 
The solution is similar to the one we’ve just described: you need to delete duplicate entries. However, the conditions are not the same, so the methods also differ:
- Look for duplicate entries in Magento 2. Most of them are situated in the database under the report_event and customer_visitor tables (look in other tables too).
- Eliminate the duplicate entries.
However, it’s not all that simple. The author of the article reports that the duplicate entry message reappeared on every data migration tool run with a different duplicate entry. The logged files of Magento contained the error-causing duplicates, so it was decided to remove the log script from the data migration tool’s config.xml file:
| 1 2 3 4 5 | <step title="Log Step">             <integrity>Migration\Step\Log\Integrity</integrity>             <data>Migration\Step\Log\Data</data>             <volume>Migration\Step\Log\Volume</volume>         </step> | 
No more duplicate errors occurred, so the migration from Magento 1 to Magento 2 was completed successfully. You can find more information here: .
The impact of MySQL foreign_key_checks on the entire database
Another subject related to integrity constraint violations in Magento 2 was touched on in a StackExchange discussion. asked whether the SET FOREIGN_KEY_CHECKS=0; command affects the whole engine or a current transaction?
answers that it is both for scope. You can set the command for a session like this:
| 1 | SET FOREIGN_KEY_CHECKS=0; | 
If you need to set globally, choose the following one:
| 1 | SET GLOBAL FOREIGN_KEY_CHECKS=0; | 
further explains that the two foreign_key_checks variables include a global variable and a local one. The latter is applied per session. Besidesб it can be initialized to the value of a global variable upon connection.
adds the following example to illustrate what the previous author said:
| 1 2 3 4 | SET FOREIGN_KEY_CHECKS=0; SET GLOBAL FOREIGN_KEY_CHECKS=0; SHOW Variables WHERE Variable_name='foreign_key_checks'; # always shows local variable | 
Bouke also adds that setting the GLOBAL variable leads to a situation when the local one isn’t changed for any existing connections. It is necessary to reconnect to enable changes. Alternatively, it is possible to set the local variable.
The author also highlights another crucial aspect: MySQL does not enforce foreign keys for re-enabled FOREIGN_KEY_CHECKS. As a result, you may be stuck with an inconsistent database even with enabled foreign keys and checks.
To make foreign keys completely consistent, add them while checking is enabled. More tips on MySQL foreign_key_checks are available .
How to disable a MySQL foreign key constraint temporarily
And we cannot talk about integrity constraint violations without providing tips on how to temporarily disable a foreign key constraint in MySQL. asks this question and describes the following situation: there are two Django models with a ForeignKey to one another. It is impossible to delete the instances of a model since it leads to an error caused by the ForeignKey constraint:
| 1 2 3 4 5 | cursor.execute("DELETE FROM myapp_item WHERE n = %s", n) transaction.commit_unless_managed()  #a foreign key constraint fails here cursor.execute("DELETE FROM myapp_style WHERE n = %s", n) transaction.commit_unless_managed() | 
Other forum users describe how to temporarily disable constraints and delete the instances. Thus, proposes to try DISABLE KEYS. The author of the answer recommends using this command:
| 1 | SET FOREIGN_KEY_CHECKS=0; | 
And don’t forget to use this one afterwards:
| 1 | SET FOREIGN_KEY_CHECKS=1; | 
According to , you can do that only for a single user mode maintenance. Otherwise, you may face data inconsistency issues. Berniey considers this approach helpful for uploading large amounts of data via a mysqldump output.
recommends disabling foreign key constraints to truncate tables:
| 1 2 3 | SET FOREIGN_KEY_CHECKS=0; TRUNCATE TABLE table;  SET FOREIGN_KEY_CHECKS=1; | 
You can find more answers here: .
 
                
								
			

 
            






