Magento – Magento 2: How to delete all categories at once

categorydatabasemagento2sql

We have been experimenting with syncing our existing database(not Magento) to Magento 2.

In the process, we have created over 1000 categories, but then we rearranged all the IDs to sync with our system. The problem is that I can no longer import the new categories as I get the error "URL key for specified store already exists." and we are getting duplicate categories now.

I think the best solution would be to clear them all out and import fresh. I found this tutorial for 1.9

https://gist.github.com/jklance/9664371

When I look at the new database I notice small differences

  1. entity_type_id is in all the old category tables but none of the new ones.

  2. new database has an additional table catalog_category_product_index_tmp

My questions are these,

  1. can I use that code I found and modify to remove entity_type_id
    and add TRUNCATE TABLE catalog_category_product_index_tmp;

  2. or is there more I need to modify?

  3. or can you provide me a clean script to remove all categories?

we only have 1 test product in the system, so no need to worry about them

Best Answer

This one worked for me in Magento ver. 2.1.0

SET FOREIGN_KEY_CHECKS = 0;

TRUNCATE TABLE catalog_category_entity;

TRUNCATE TABLE catalog_category_entity_datetime; 
TRUNCATE TABLE catalog_category_entity_decimal; 
TRUNCATE TABLE catalog_category_entity_int; 
TRUNCATE TABLE catalog_category_entity_text; 
TRUNCATE TABLE catalog_category_entity_varchar; 
TRUNCATE TABLE catalog_category_product; 
TRUNCATE TABLE catalog_category_product_index;

INSERT INTO `catalog_category_entity` (`entity_id`, `attribute_set_id`, `parent_id`, `created_at`, `updated_at`, `path`, `position`, `level`, `children_count`) VALUES ('1', '0', '0', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, '1', '0', '0', '1'),
('2', '3', '1', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, '1/2', '1', '1', '0');

INSERT INTO `catalog_category_entity_int` (`value_id`, `attribute_id`, `store_id`, `entity_id`, `value`) VALUES 
('1', '69', '0', '1', '1'),
('2', '46', '0', '2', '1'),
('3', '69', '0', '2', '1');

INSERT INTO `catalog_category_entity_varchar` (`value_id`, `attribute_id`, `store_id`, `entity_id`, `value`) VALUES 
('1', '45', '0', '1', 'Root Catalog'),
('2', '45', '0', '2', 'Default Category');

SET FOREIGN_KEY_CHECKS = 1;

DELETE FROM url_rewrite WHERE entity_type = 'category';
Related Topic