Drop a column from the table using db_schema.xml in Magento 2.

In Magento 2, You can create a new table using db_schema.xml file. The table contains many columns based on your requirements.

Check the blog for, How to creates a new database table.

In the future, if you want to remove or drop some column from an existing table you can simply drop a column using db_schema.xml file.

Let’s assume, You have created a table name, my_custom_table in the database with email column and you want to remove email column.

Table with a list of entry and some of the columns you don’t require, You can remove those columns using attribute disabled=true in a db_schema.xml file.

Example for remove column,
email column.
<column xsi:type=”varchar” name=”email” nullable=”true” length=”255″ comment=”Email”/>

Drop email column using disabled=”true”,
<column xsi:type=”varchar” name=”email” nullable=”true” length=”255″ comment=”Email” disabled=”true”/>

But only disabled=”true” is not enough to remove/drop column from table. You must first generate a db_schema_whitelist.json file to remove a column from the table.

You can read more details about the db_schema_whitelist.json file.

php bin/magento setup:db-declaration:generate-whitelist –module-name=Vendorname_Packagename¬† (double hyphen before module-name in command)

Where Vendorname_Packagename is your vendor and module name.

This file provides a history of all tables, columns, and keys added with declarative schema using a specific module.

Run below command to drop a column(Before run setup:upgrade command, verify you must have run above setup:db-declaration:generate-whitelist command),
php bin/magento setup:upgrade

Now when seeing your table your column will be removed.