Milind Daraniya

How to Add a New Column to an Existing Table Using db Schema in Magento 2.4+ ?

Published September 16th, 2023 8 min read

In Magento 2, the database schema is defined using XML files that describe the structure of database tables. To add a new column to an existing table, you can create a new database schema file and run the data migration to apply the changes. In this tutorial, we'll guide you through the process of adding a new column to an existing table in Magento 2.

Create a New Database Schema File

  1. Inside your custom module, create a new db_schema.xml file in the Setup directory. If the Setup directory does not exist, create it.
  2. In the db_schema.xml file, define the new column to be added to the existing table. For example, if you want to add a column named custom_field to the sales_order table, the db_schema.xml file would look like this:
<?xml version="1.0"?>
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
    <table name="sales_order" resource="sales" engine="innodb" comment="Sales Order">
        <column xsi:type="varchar" name="custom_field" nullable="true" length="255" comment="Custom Field"/>
    </table>
</schema>

Run the Command

Now, you can run the command to apply the new column to the existing table. Run the following command from the Magento root directory:

php bin/magento setup:upgrade