Magento – Magento 2 : Unique constraint violation found when adding product, categories or mega menu items

databasemagento2.2.3url-rewrite

I have a Magento 2.2.3 installation and I have the theme SM-Maxshop on that. I am not able to add any products, categories or Megamenu items to it. I get an error "Unique constraint violation found" when I do any of these operations. I was able to add custom product attributes and add them to attribute sets too, but am stuck after that. Has anyone else faced any issue like this?

PFA screenshots of the error pages.
Add new category in Magento error
Add new product in Magento 2
Add menu items Magento 2.2.3

I see this in the exception.log file:

I see this entry in exception.log:

[2018-05-14 05:36:06] main.CRITICAL: Unique constraint violation
found {"exception":"[object]
(Magento\Framework\Exception\AlreadyExistsException(code: 0):
Unique constraint violation found at
/home/…/public_html/…/vendor/magento/framework/EntityManager/Operation/Create.php:134,
Magento\Framework\DB\Adapter\DuplicateException(code: 1062):
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry
'0' for key 'PRIMARY', query was: INSERT INTO url_rewrite
(redirect_type,is_autogenerated,metadata,description,store_id,entity_type,entity_id,request_path,target_path)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?), (?, ?, ?, ?, ?, ?, ?, ?, ?), (?,
?, ?, ?, ?, ?, ?, ?, ?), (?, ?, ?, ?, ?, ?, ?, ?, ?), (?, ?, ?, ?, ?,
?, ?, ?, ?) at
/home/…/public_html/…/vendor/magento/framework/DB/Adapter/Pdo/Mysql.php:555,
Zend_Db_Statement_Exception(code: 23000): SQLSTATE[23000]: Integrity
constraint violation: 1062 Duplicate entry '0' for key 'PRIMARY',
query was: INSERT INTO url_rewrite
(redirect_type,is_autogenerated,metadata,description,store_id,entity_type,entity_id,request_path,target_path)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?), (?, ?, ?, ?, ?, ?, ?, ?, ?), (?,
?, ?, ?, ?, ?, ?, ?, ?), (?, ?, ?, ?, ?, ?, ?, ?, ?), (?, ?, ?, ?, ?,
?, ?, ?, ?) at
/home/…/public_html/…/vendor/magento/zendframework1/library/Zend/Db/Statement/Pdo.php:235,
PDOException(code: 23000): SQLSTATE[23000]: Integrity constraint
violation: 1062 Duplicate entry '0' for key 'PRIMARY' at
/home/…/public_html/…/vendor/magento/zendframework1/library/Zend/Db/Statement/Pdo.php:228)"}
[]

Best Answer

Probably your AUTO_INCREMENT is set wrong for the table. You can check this with:

SELECT 
`AUTO_INCREMENT`
FROM  INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'db_name'
AND   TABLE_NAME   = 'table_name';

You can then fix the auto increment by setting it the the highest ID +1

ALTER TABLE table_name AUTO_INCREMENT = start_value;
Related Topic