How to create a table in a database using DB schema in Magento 2?

Today, We are going to learn How to Create Custom Table (via XML) in Magento 2.

For creating the custom table :

First, create a file in app\code\Vendor\Extension\etc\ directory db_schema.xml and add following code:

<?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="contact_details" resource="default" engine="innodb" comment="Comment Here">
        <column xsi:type="smallint" name="id" nullable="false"  comment="ID"/>
        <column xsi:type="varchar" name="name" nullable="false" length="255" comment="name"/>
        <column xsi:type="varchar" name="email" nullable="false" length="255" comment="email"/>
        <column xsi:type="varchar" name="lname" nullable="false" length="255" comment="lname"/>
        <column xsi:type="int" name="telephone"  unsigned="true" nullable="false" comment="telephone"/>
        <column xsi:type="varchar" name="insta_user_name" nullable="false" length="255" comment="insta_user_name"/>
        <column xsi:type="varchar" name="no_insta_follower" nullable="false" length="255" comment="no_insta_follower"/>
        <column xsi:type="varchar" name="insta_follower" nullable="false" length="255" comment="insta_follower"/>
        <column xsi:type="varchar" name="comment" nullable="false" length="255" comment="comment"/>
        <constraint xsi:type="primary" referenceId="PRIMARY">
            <column name="id"/>
        </constraint>
    </table>
</schema>

After completing the above step now we only need to execute the upgrade command given below:

php bin/magento s:up

When the setup upgrade command completes, a new database table will be created in your database.

Note: This method for creating a custom table using XML will be working only in Magento 2.3 and the greater versions.

I hope that you found this Blog helpful. If you’ve any queries, please leave comments in the comment section.

Thanks for following and reading this blog.

sexpoundsofttechsolution

How to create a table in a database using DB schema in Magento 2

How to create a table in a database using DB schema in Magento 2