4.6 (91.11%) 45 votes


You will follow these steps to Create and Upgrade Database in Magento 2:

  1. Install Schema
  2. Install Data
  3. Upgrade Schema
  4. Upgrade Data

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:

php bin/magento setup:upgrade

In this topic, we will use these classes to setup database for Magestore_

  1. Install Schema

We use module vendor Magestore and module name is DataExample.

Create file: app/code/Magestore/DataExample/Setup/InstallSchema.php

In this file, we created a table has name “data_example” with 4 columns: example_id, title, content, created_at with data types are interger, varchar, text, timestamp

You can review all data types in this file: \Magento\Framework\Db\Ddl\Table.php

  1. Install Data

File: app/code/Magestore/DataExample/Setup/InstallData.php

In this file we insert a row with value for “title” and “content” columns to data_example table.

  1. Upgrade Schema

File: app/code/Magestore/DataExample/Setup/UpgradeSchema.php

Note: We have to check module version of in upgrade function. In this example we upgraded module from version 1.0.0 to 1.0.1. Drop created_at column from data_example table.

  1. Upgrade Data

File: app/code/Magestore/DataExample/Setup/UpgradeData.php


These are all steps to Create and Upgrade Database in Magento 2. Hope all you guys can learn magento 2 easier with our series lesson.

The 4 steps I mention above is the shortest process for you to Create and Upgrade Database in Magento 2. With this guide, you can manage the Database in Magento 2 easily.

Thank you for reading this post.

Magento 2 Upgrade: How To & Two Ways to Upgrade Magento 2.0.0 to 2.0.2?
How to Update Your Magento 2 Installation

Comments are closed.