Why I Use Plain SQL Files for Database Migrations

Why I moved from framework migration DSLs to plain SQL files with a small runner, especially for zero-downtime index builds in PostgreSQL.

· 3 min read · Erik Kubica

Where Migration DSLs Got Awkward for Me

Most web frameworks come with their own schema migration DSL.

In Ruby, you write ActiveRecord migrations. In PHP, you write Phinx or Laravel schema blueprints. In Node, you write Knex, TypeORM, or Prisma schema definitions.

They feel great during the first few weeks of a greenfield project. You write $table->string('email') in PHP or table.string('email') in TypeScript, run artisan migrate or prisma migrate deploy, and your local database updates.

Then the product grows. You have 8 million rows in an orders table on a primary database server. You need to add a column and build an index without dropping incoming traffic during a deployment.

That is where I started to run into trouble with migration DSLs.

In my experience, migration DSLs are great for simple changes, and less so when a production database needs precise, dialect-specific SQL.

The Production Table Lock

When you add an index using an ORM migration tool:

// A typical TypeORM / Knex migration
export async function up(knex: Knex): Promise<void> {
    await knex.schema.alterTable('orders', (table) => {
        table.index(['customer_id', 'created_at']);
    });
}

It is worth checking what SQL that generates:

CREATE INDEX orders_customer_id_created_at_index 
ON orders (customer_id, created_at);

In PostgreSQL, a standard CREATE INDEX blocks writes to the table while the index builds. For an 8-million-row table, that build might take 45 seconds.

During those 45 seconds, every INSERT, UPDATE, and DELETE on your orders table waits. Incoming web requests stall, connection pools fill up, and within 15 seconds your Nginx reverse proxy can start returning 504 Gateway Timeouts.

Postgres has a native mechanism for this: CREATE INDEX CONCURRENTLY. But because CONCURRENTLY cannot run inside an outer transaction block, some ORM migration runners fail on it or work around it awkwardly. Some tools do support it with a flag or a raw SQL step, so check what yours offers.

Plain SQL Migrations

About six years ago I started writing plain SQL migration files on my projects:

-- migrations/0042_add_orders_customer_idx.sql
-- Step 1: Set a strict lock timeout so we never hang the app
SET lock_timeout = '2s';

-- Step 2: Build the index concurrently without blocking writes
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_orders_customer_created 
ON orders (customer_id, created_at DESC);

It is easy to read. A database administrator can review the git diff in a few seconds, and there is no transpilation layer or abstraction to second-guess.

To execute them, you do not need a Node.js runtime or framework dependencies. You can use a lightweight Go binary like golang-migrate, or a small runner of about 45 lines using a simple schema_migrations tracking table:

-- A simple schema tracking table
CREATE TABLE IF NOT EXISTS schema_migrations (
    version text PRIMARY KEY,
    applied_at timestamptz DEFAULT now()
);

When my deployment script runs, it reads the .sql files in lexicographical order, checks whether the version exists in schema_migrations, executes the file inside a transaction (or standalone for concurrent operations), and records the timestamp.

On my setup the runner finishes in about 8ms on a $12 server and uses around 6 MB of RAM.

SQL Outlives Frameworks

In 13 years of backend work, I have seen teams move from CodeIgniter to Symfony to Laravel, or from Express to NestJS to Fastify.

When they switched frameworks, the old migration history often could not be reused, and they had to dump the schema to raw SQL and start over.

Plain SQL is portable between Go, Python, PHP, Rust, and bash. A framework's migration tool is still a fine choice for many projects, especially smaller ones. If you hit the locking problem above, or you expect to change frameworks, plain SQL files are worth a try.

Tell me what you need built

Usually a reply within a day, by email or WhatsApp.