How to add or drop a column from a table in Magento 2?

Part 3: to continue series of database operation, how to add a column or delete a column from database table in Magento 2 using declarative schema.

Add a column to Table:

Modify your module db_schema.xml file to add a new column in the database table.

db_schema.xml:

Generate db_schema_whitelist.json file:

When adding a new column to the table, remember to regenerate the db_schema_whitelist.json file so it contains the new column name too.

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

Run upgrade command:

Validate your DB table for the new column, it should already be created in the table.

Drop a column from Table:

To drop a column from the DB table you can modify that module  db_schema.xml file. There are 2 ways to delete a column.

  1. Delete itself that column node from db_schema.xml file and save the file.
  2. Add an attribute to that column node disabled=”true” and save the file.

Db_schema.xml:  in given example deleting created_at column from table by adding disabled attribute in column.

Run upgrade command:

NOTE: You can not delete a table column if it does not exist in the db_schema_whitelist.json file of that module.

Leave a Reply

Your email address will not be published.