— Technical
Checking if a database table exists in Magento 2 before running queries
30 October 2023 · 3 min read
This is a short one, but it comes up constantly in upgrade scripts and data patches: you need to run a query against a table that may or may not exist depending on which modules are installed or what state the upgrade process is in.
Running a query against a non-existent table throws a fatal SQL error and halts the setup upgrade. The fix is a single method call before you execute.
The pattern
<?php
declare(strict_types=1);
namespace YourVendor\YourModule\Setup\Patch\Data;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Setup\Patch\DataPatchInterface;
class YourDataPatch implements DataPatchInterface
{
private const TARGET_TABLE = 'catalog_product_entity_varchar';
public function __construct(
private readonly ResourceConnection $resourceConnection
) {}
public function apply(): void
{
$connection = $this->resourceConnection->getConnection();
$tableName = $connection->getTableName(self::TARGET_TABLE);
if (!$connection->isTableExists($tableName)) {
return;
}
// Safe to query now
$connection->query("UPDATE {$tableName} SET ...");
}
public static function getDependencies(): array
{
return [];
}
public function getAliases(): array
{
return [];
}
}
isTableExists() queries the information schema to confirm the table is present in the current database. It’s a lightweight check — a single metadata query — and it’s the correct guard for any SQL operation in a context where table existence isn’t guaranteed.
Where this actually matters
Data patches and upgrade scripts. If your patch depends on a table created by another module’s schema patch, execution order during setup:upgrade isn’t always guaranteed the way you’d expect. A guard here prevents a hard failure if your patch runs before its dependency.
Cross-module queries. If your module queries a table from a third-party extension, that extension might not be installed on every deployment. isTableExists() lets your module degrade gracefully rather than failing hard.
Post-upgrade cleanup scripts. Scripts that clean up or migrate data from tables that may have been dropped by a prior upgrade step need this check. A table that existed in version N may not exist in version N+1.
Don’t use it as a substitute for proper dependencies
isTableExists() is a guard, not an architecture. If your module has a genuine dependency on another module’s tables, declare the dependency in module.xml via <sequence>. The existence check is for situations where the dependency is optional or where you’re handling a degraded state gracefully — not for working around missing <sequence> declarations.
The check itself is one line. The discipline of knowing when to use it versus fixing the dependency declaration is the actual skill.
Savan Padaliya
Senior Engineering Consultant