How to drop and rename a database table in Magento 2?

Part 2: Continued to the series post of  Database operation in Magento 2. In this post, I am going to cover: how to rename and drop a database table.

Rename a table:

As in the last post we created a table name “custom_form”, using a declarative schema. Here we are going to rename the same table and migrate data from that table to the new table.


The declarative schema will create a new table with the new name and drop the table with the old name. To migrate data from another table, specify the onCreate attribute on the table declaration, and add specify the source table name:

db_schema.xml:

onCreate=”migrateDataFromAnotherTable(custom_form)”

here csutom_form table is source table name.

Generate db_schema_whitelist.json file:

When renaming a table, remember to re generate the db_schema_whitelist.json file so it contains the new name in addition to the old one.

php bin/magento setup:db-declaration:generate-whitelist --module-name=MM_Db

Here MM_Db is my module name. Please replace it with your Module name.

Run upgrade command to create table:

php bin/magento setup:upgrade

Validate your DB for the new custom table, it should already be created in the DB with data migration.

Drop a module table:


To drop a module table just comment out table code from db_schema.xml file.

Run upgrade command to drop a table:

php bin/magento setup:upgrade

Validate your DB, it should already be deleted from the DB.

Leave a Reply

Your email address will not be published.