It is inevitable that your Magento version; hosted by your server or cloud environment; will be updated at some point, due to being pushed by software or hardware upgrades, and there might be some rare scenarios that after an upgrade you will get the following error after executing some regular operations on both frontend and backend:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry

Normally, when getting this error, the common solution is to check the database for the following:

  • If you know which tables are involved in the executed process; check that the increment property is correctly set in the corresponding column.
  • Check for any unique property set in a column that is not allowing to insert/update new data.

However, the above solutions require a deeper understanding of Magento’s database structure, and changing the database manually might be risky, it might lead to data loss if you are not careful.

Luckily, there are scenarios that might not require such dangerous troubleshooting. For example, if the error is caused when saving/updating a product with Tier Price you would need to search for the module processing the update and check if the store scope is explicitly set by using calling setCurrentStore(), similar to this:

$this->_storeManager->setCurrentStore(0);

$this->_productRepository->save($product);

And just make the following modification for using the deprecated getResource()->save() function instead of the recommended Product Repository:

$this->_storeManager->setCurrentStore(0);

$product->getResource()->save($product);

//$this->_productRepository->save($product);

By using the deprecated getResource()->save() function Magento will overcome this issue and save the product normally, but of course, it would reduce performance a little bit by not using the ProductRepository.

At the moment of writing this article, there is no official plugin that addresses this issue on the ProductRepository, but at least it will allow you to avoid direct changes in the database. 

Another situation that would trigger the Duplicate Entry error is when trying the save a CMS page, but fortunately, Magento already released the patch MDVA-33606 for version 2.4.1:

MDVA-33606: solves the issue where the users get Unique constraint violation found error when saving a CMS page assigned to hierarchy tree. 

Finally, for applying a patch you must follow the instructions for your specific Magento version. The present article will not cover the different methods for applying a patch. If your Magento version is lower than 2.4.1 you can still check out the official Magento patch information and implement a similar solution to your version.

Happy coding!