March 10, 2021 | 10 min read

How to Add a New Table to a Database in Magento Module

This tutorial applies to Magento 2.2.x only. For Magento 2.3.x, see Declarative

1. QuickRead

Magento 2 has a special mechanism that allows you to create database tables, change existing ones, and even add some data to them (like setup data, which has to be added when a module is installed). This mechanism enables these modifications to be transferable between various installations.
The main concept is that instead of performing manual SQL operations that you have to do again and again when reinstalling the system, developers are creating an install (or upgrade) script that contains the data. The script will run any time a module is installed.
In the previous post, we learned how to build a single custom module. Following the previous tutorial, we will learn how to build a database table in Magento 2.
This is a very simple tutorial, but it’s very relevant. You’re going to apply it a lot. Let’s get started!

2. File Structure of Module

We’ve updated our File Module structure as follows:
table_db_img1

3. Create file module.xml and registration.php

For the job of creating these 2 files, I have detailed instructions and explanations in the previous article. You can read it here.

4. Create file InstallSchema.php

You create this file according to the path: Oscprofessionals/Mymodule/Setup/InstallSchema.php.
We will create a table name magetop_blog with fields: id, title, description, created_at, status.
use Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
class UpgradeSchema implements UpgradeSchemaInterface
We will insert data for the oscp_blog_categories table.