Need to store data that doesn’t fit neatly into Magento’s existing tables? Creating Magento 2 custom database tables is a straightforward way to support new features while keeping your data organized. With Magento’s declarative schema, you can define a table, add columns, and manage database changes right in your module.
This guide walks you through the essentials, from setting up your module’s schema file to applying the changes and checking that your table is ready to use. Whether you’re building a small customization or a larger extension, you’ll learn an approachable way to create custom tables in Magento 2.
Plan Your Magento 2 Custom Database Tables
Before changing a schema file, take a moment to decide what the new data needs to do. A clear plan helps keep the table focused, avoids unnecessary overlap with Magento’s existing data, and makes future updates easier to manage.
Start by connecting the data you want to store with the Magento feature that will use it. The module’s responsibility and the table’s purpose will guide its name, structure, and relationships.
Choose a module and define the table’s purpose
Place the table in the module that owns the feature and its data. For example, a module that records customer-submitted product questions could own a table for those questions, while a separate reporting module should not take ownership of that same data simply because it displays it.
Write down what one row represents and which parts of the application will read or update it. Check whether an existing Magento entity or table already meets the need; custom storage is most useful when the information has its own lifecycle or does not naturally belong to an existing entity. Choose a distinct, descriptive table name, and avoid editing Magento core tables.
Once ownership is clear, sketch the records the feature must save and retrieve. This turns the table design into a practical list of fields and lookup patterns rather than a collection of guesses.
Identify columns, data types, keys, and indexes
For each field, note its purpose, whether it is required, and the kind of values it will hold. A typical table might include an auto-incrementing identifier, a related entity ID, a status, and creation and update timestamps. Select types that fit the expected values, and define sensible defaults and nullability.
Then consider how the application will query the data. Use a primary key to identify each row, and add indexes for columns frequently used in filters or joins. For example, if the feature often retrieves records by customer ID and status, those access patterns should inform the index design. Add a foreign key only when its relationship and deletion behavior are appropriate.
- Keep column names clear and consistent with Magento conventions.
- Avoid storing multiple values in one column when they need to be searched or updated separately.
- Index for real query needs; unnecessary indexes can slow writes.
Finally, confirm that the project’s software stack can process the schema definition you plan to use. Compatibility depends on the Magento release as well as the PHP and database versions installed.
Check Magento and PHP version requirements
Declarative schema is available from Magento Open Source and Adobe Commerce 2.3 onward. If the project runs an older release, its schema setup approach may differ, so check the version before following current examples. Also verify the project’s PHP and database versions against Adobe’s Commerce system requirements.
These checks are especially useful when preparing a module for more than one Magento release. Confirm supported versions in the module’s compatibility targets, then test schema installation and upgrades in a development environment before deploying changes.
Create Magento 2 Custom Database Tables with Declarative Schema
With the table’s purpose and fields planned, the next step is to translate that design into a module-level schema. A small XML definition gives Magento a repeatable way to create and update the structure during installation and upgrades.
The schema belongs to the module that owns the feature, so Magento can track its changes alongside the module’s code. Start by adding the expected file and declaring the table within it.
Add the dbschema.xml file to your module
Create etc/dbschema.xml in your module, for example, app/code/Vendor/Questions/etc/dbschema.xml. The file’s root element must use Magento’s declarative schema definition, and each table needs a unique name and a short comment.
This example shows the basic structure; add columns and constraints inside the table element:
<?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="vendorquestion" resource="default" engine="innodb"
comment="Product Questions">
<!-- Add columns, constraints, and indexes here -->
</table>
</schema>Use your module’s vendor-specific prefix to reduce the risk of name collisions with other extensions.
Inside the table element, declare every field explicitly so the database structure reflects the feature’s actual needs. The following choices establish how rows are identified and how Magento can retrieve them efficiently.
Define columns, constraints, and indexes
For example, an entityid column can use xsi:type="int", identity="true", and nullable="false" for an auto-incrementing identifier. Add a primary constraint that references this column, then define the feature’s other fields with suitable types, lengths, defaults, and nullability.
Indexes should match frequent query patterns, such as looking up questions by product ID and status. Give each constraint and index a stable referenceId; it helps Magento identify the schema object when applying later changes. Avoid adding indexes “just in case,” since they add work to database writes.
Once the XML is saved, Magento needs to recognize the module and process its schema declaration. Run these steps in a development environment first, then verify the result before deploying.
Register the module and apply the schema
Make sure the module has its registration.php and etc/module.xml files, then enable it and run the upgrade command:
bin/magento module:enable VendorQuestions
bin/magento setup:upgradeUse the project’s actual module name in place of VendorQuestions. After the command completes, inspect the database to confirm the table, columns, and indexes match the declaration; review the CLI output for errors before proceeding.
For changes that remove existing schema objects, one additional file may be important. Magento uses a whitelist to recognize which declared objects belong to the module and may be safely removed.
Generate a whitelist for schema changes when needed
Generate the whitelist after defining the module’s schema by running:
bin/magento setup:db-declaration:generate-whitelist --module-name=VendorQuestionsThis creates or updates etc/dbschemawhitelist.json. Commit that file with the schema change, particularly when removing a table or column, and test destructive updates on a database copy before applying them to production.
Verify and Use Your New Database Table
A successful setup command is a good sign, but it does not confirm that the table is ready for your feature. Check the database first, then connect the schema to Magento’s model and resource-model layers so the application can work with records cleanly.
Start with a direct check of the database structure and Magento’s setup output. This helps distinguish a schema issue from a problem in the PHP code that uses the table.
Confirm the table was created successfully
Use your database client or administration tool to confirm the table exists in the expected database. Check that its columns, primary key, defaults, and indexes match etc/dbschema.xml; a table with the right name can still have an incomplete structure.
You can also inspect Magento’s setup output and run bin/magento setup:db:status to check whether module schema declarations are pending. If the table is missing, confirm that the module is enabled and that the upgrade command completed without errors before changing application code.
Once the structure checks out, give Magento a pair of classes to represent records and handle database access. Keep business rules out of the resource model; its job is to map the model to the table.
Add a resource model and model for database operations
Create a model class extending AbstractModel and initialize it with a resource model. The resource model extends MagentoFrameworkModelResourceModelDbAbstractDb and identifies the table and primary-key column:
protected function construct()
{
$this->init('vendorquestion', 'entityid');
}In the model’s construct() method, call $this->_init(VendorQuestionsModelResourceModelQuestion::class). Use dependency injection when obtaining these classes—avoid the ObjectManager directly. For larger features, expose operations through a repository or service contract rather than letting controllers access resource models.
With both classes in place, the feature can persist records through Magento’s resource layer. The following pattern illustrates the basic operations; production code should also validate input and handle exceptions.
Insert, retrieve, update, and delete records
Inject the model factory and resource model where they are needed. Create a model, set its data, and save it; to retrieve an existing record by ID, load it through the resource model:
$question = $this->questionFactory->create();
$question->setData($data);
$this->resource->save($question);
$this->resource->load($question, $id);After loading, check getId() before using the record. Change permitted fields and call save() to update; call delete() to remove it. Apply authorization and ownership checks before updates or deletions, and prefer repository methods in application-facing code.
If a command or database operation fails, narrow down the cause by checking the schema, module configuration, and generated code separately. These common checks often reveal the issue quickly.
Troubleshoot common schema and setup errors
Review the CLI error message first, then check for XML typos, duplicate table names, invalid column types, or missing referenceId values. If Magento reports pending changes, rerun setup after confirming the schema file is in the correct module.
- Table not found: verify the module is enabled and the table name matches the resource model.
- Access or connection errors: check database credentials and the configured database resource.
- Upgrade or removal problems: confirm the whitelist is committed and test destructive changes on a database copy.
Build Magento 2 Custom Tables with Confidence
Creating Magento 2 custom database tables is easier when you start with a clear purpose, design around real data and query needs, and keep the schema in the module that owns the feature. Declarative schema makes changes manageable, while careful verification and Magento’s model and resource-model layers help your code work with the data reliably.
Test schema updates and database operations in development before deploying, especially when a change could remove existing data. With these practices in place, you can add storage that supports your feature today and remains easier to maintain as your store evolves.