How to Create and Upgrade Database in Magento 2

How to Create and Upgrade Database in Magento 2

Managing database is essential for any platform and Magento 2 E-commerce store is no exception! One may want to add a new database or update the existing ones. Add new rows or columns or delete particular data from the database and manage the database easily in Magento 2.

I have come up with a process to create and upgrade database in Magento 2 the easy way. Hope it is helpful.

Steps to create a database and upgrade in Magento 2:

Magento 2 provides some classes in the directory app/code/[Namespace]/[ModuleName]/Setup to create or upgrade database.

  • InstallSchema – setup database structure
  • InstallData – initial the data for database table.
  • UpgradeSchema – upgraded database structure
  • UpgradeData – upgraded (add/remove) data from table.

Functions of these classes will be run when we install or upgrade module by this command line:

Elaborating each step,

  1. Install Schema
    Create file: app/code/Meetanshi/HelloWorld/Setup/InstallSchema.php
    In this file, we created a table with name “data_example” with four columns: example_id, title, content, created_at with data types are integer, varchar, text, timestamp
    You can review all data types in this file: \Magento\Framework\Db\Ddl\Table.php
  2. Install Data
    File: app/code/Meetanshi/HelloWorld/Setup/InstallData.php
    Here,  we insert a row with value for “title” and “content” columns to data_example table.
  3. Upgrade Schema
    File: app/code/ Meetanshi/HelloWorld/Setup/UpgradeSchema.php
    Here, note that we have to check module version in upgrade function. In this example, we upgraded module from version 1.0.0 to 1.0.1. Drop created_at column from the data_example table.
  4. Upgrade Data
    File: app/code/ Meetanshi/HelloWorld/Setup/UpgradeData.php

Play with your database and control it easily in your Magento 2 store:)
Let me know if you have any doubts in the Comments below and I’ll help you out to solve it. Rate my article with 5 stars if you find it useful.

(based on 3 Reviews)

Sanjay is a co-founder at Meetanshi. He is a Certified Magento Developer who loves creating Magento E-commerce solutions. When he is not engrossed with anything related to Magento, he loves to play cricket.