Is there any way that I can assign products to category using SQL in code? Currently, Category Result Sets are too large, the request gets heavy, so unable to save a Category the traditional way.

2 Answers 2


Category and Products are mapped on catalog_category_product table.

Where there are 4 columns: entity_id, category_id, product_id, position.

Where entity_id is the auto-increment column .

So you can run this by Sql:

    INSERT INTO `catalog_category_product`(`category_id`, `product_id`) 
    VALUES ('category_id','product_id');

You can use it by simple corePHP program like:

  1. Create A temporary table on your database having 4 columns ('id', 'category_id', 'product_id', 'flag') and stored data.
  2. Create a PHP file on root, and Connect to database.
  3. SELECT from this temporary table and INSERT into catalog_category_product table and if update success update flag.
  • Hello, how to use it in program ?
    – devhs
    Commented Apr 20, 2021 at 4:31
  • I hope Now you better Understand it.
    – smruti
    Commented Apr 20, 2021 at 8:48
  • Thankyou for the answer
    – devhs
    Commented Apr 20, 2021 at 9:25

You can also assign products to category programmatically by using CategoryLinkManagementInterface By this way.

  * @var CategoryLinkManagementInterface
 protected $categoryLinkManagement;
 public function __construct(
     \Magento\Catalog\Api\CategoryLinkManagementInterface $categoryLinkManagementInterface
 ) {
     $this->categoryLinkManagement = $categoryLinkManagementInterface;
public function execute()

By Using object Manager

categoryLinkManagement = \Magento\Framework\App\ObjectManager::getInstance()

  • When there are more then 1000+ products to execute with this function it gets 504 not found error
    – devhs
    Commented Apr 20, 2021 at 9:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.