Skip to content

Zero-Downtime Schema Migrations ​

"An ACCESS EXCLUSIVE lock is acquired unless explicitly noted." — PostgreSQL 19 Documentation, ALTER TABLE

Summary: A migration is a lock request first and a change second; zero downtime comes from short, bounded, individually compatible steps, not from a clever single statement. Focus: Which ALTER forms rewrite or lock in PostgreSQL and MySQL, the lock queue, lock_timeout and retry, expand/contract with dual writes and batched backfills, constraints and indexes online, replicas, tooling in Go and Laravel, and how to test and release migrations. Learning goal: Take any schema change on a busy table and split it into steps that never hold a long lock, never break a running application version, and can be paused or abandoned safely.

This page is the complete reference for changing a schema while traffic keeps flowing. It covers every common change (add, drop and rename columns, defaults, NOT NULL, CHECK and foreign keys, indexes, type changes, enums, partitions), what each costs in lock level and rewrite on PostgreSQL, what MySQL InnoDB does with its INSTANT, INPLACE and COPY algorithms and with gh-ost and pt-online-schema-change, how SQL Server, Oracle, SQLite, CockroachDB, MongoDB and Redis differ, and how Go and Laravel tooling runs, retries and lints migrations. It deliberately does not re-teach three neighbours: lock modes and pg_locks are in Locks & Concurrency, batch-backfill mechanics on huge tables are in Billion-Row Tables, and replication lag and failover are in Replication, Read Replicas & Failover. What a column should look like in the first place belongs to Schema Design; which index to build belongs to Indexing; the message-side version of the same problem is Message Design & Schema Evolution.

Page map ​

If you are looking forGo to
Which ALTERs rewrite the table and which are metadata-onlyEverything in one minute, Rewrite or metadata-only
Why an instant ALTER can still cause an outageThe lock queue
lock_timeout plus retrylock_timeout and retry
Expand, migrate, contract; dual writes; backfillExpand / migrate / contract, Dual writes, Backfill
NOT VALID, VALIDATE, adding NOT NULL safelyConstraints in two steps, NOT NULL safely
Index builds, INVALID indexes, REINDEX CONCURRENTLYIndexes online
Rename, change type, drop, default, enumRenames, Type changes, Dropping columns, Defaults, Enums
Huge UPDATEs and replicasLarge UPDATEs, Replicas
Transactional DDL in PostgreSQL vs MySQL implicit commitTransactional DDL
MySQL INSTANT/INPLACE/COPY, gh-ost, pt-oscMySQL online DDL, gh-ost and pt-osc
Other enginesWhat each database really does
Laravel, Go, golang-migrate, goose, Atlas, sqitch, Flyway, Liquibase, pgroll, Reshape, squawkTooling
Recipes with SQL + Go + LaravelSolving the classic problems
Rollback, feature flags, blue/green, testing on a copyRelease strategy, Testing
Monolith to distributedIn architecture
Reproduce a blocked queueLab

Everything in one minute ​

What each change costs on PostgreSQL (from the PostgreSQL 19 ALTER TABLE and CREATE INDEX pages; every row is unpacked later).

ChangeLockTable rewrite?Safe pattern
ADD COLUMN nullable, no defaultACCESS EXCLUSIVE, briefNoPlain, with lock_timeout
ADD COLUMN ... DEFAULT <constant> (PostgreSQL 11+)ACCESS EXCLUSIVE, briefNo: default stored in the catalogPlain, with lock_timeout
ADD COLUMN with a volatile default, stored generated column, identity columnACCESS EXCLUSIVE, whole rewriteYes, plus indexesAdd nullable, backfill in batches
DROP COLUMNACCESS EXCLUSIVE, briefNo; space reclaimed laterStop using it one release earlier
RENAME COLUMN / RENAME TOACCESS EXCLUSIVE, briefNoTwo deploys or a view, because running code still uses the old name
SET NOT NULLACCESS EXCLUSIVE plus a scanNo, but scans (skipped if a valid CHECK proves it, PostgreSQL 12+)CHECK ... NOT VALID, VALIDATE, then SET NOT NULL
ADD CHECKACCESS EXCLUSIVE plus a scanNoNOT VALID, then VALIDATE CONSTRAINT
ADD FOREIGN KEYSHARE ROW EXCLUSIVE on both tables plus a scanNoNOT VALID, then VALIDATE CONSTRAINT
ALTER COLUMN ... TYPEACCESS EXCLUSIVENormally yesNew column, dual write, backfill, swap
CREATE INDEXSHARE (blocks writes)n/aCREATE INDEX CONCURRENTLY

Where the damage comes from.

MythReality
"The ALTER takes 5 ms, so it is safe."The ALTER may wait for minutes behind an old transaction, and every later query waits behind the ALTER.
"Lock the table, change it, unlock it."Hold ACCESS EXCLUSIVE only for a catalog change; do scans and rewrites in steps that take weaker locks.
"Roll back with down()."Once new data exists, down() destroys it; roll forward or flip a flag.

The five things to do, in order.

RuleWhy
1. SET lock_timeout (and retry) before every DDL on a live tableThe queue behind a waiting ALTER is the outage
2. Never combine a rewrite and a lockAdd nullable, backfill, then constrain
3. Every release must work with the schema before and after itRolling deploys run two versions at once
4. Backfill in short batches, throttled by replica lagOne huge UPDATE means bloat, WAL bursts and lag
5. Drop last, in a later releaseNothing is destroyed until you are sure

Why migrations are dangerous ​

A schema change is the one operation that touches every query on a table at once. Ordinary writes take row locks that only collide with writes to the same rows. DDL takes a table-level lock that collides with everything, and most ALTER TABLE forms need the strongest mode, ACCESS EXCLUSIVE, which conflicts with every other mode including the ACCESS SHARE a plain SELECT takes. Lock modes themselves are taught in Locks & Concurrency; this page uses them as a cost model.

Simple, risky approachSafe approach
One migration, one transaction, one deploySeveral small steps, each its own deploy or job
Rely on the DDL being fastBound the wait with lock_timeout, retry
Constraint added with a full scan under a heavy lockNOT VALID first, validate with a weak lock
Rewrite in one statementNew column, dual write, batched backfill
down() to undoForward-only fixes and feature flags
HopeLint in CI, rehearse on a copy of production

The analogy we reuse on this page: replacing a bridge while traffic crosses it. You do not close the road, tear up the old bridge and build a new one. You build the new bridge beside it, move a few cars across, watch it hold, move everyone over, and only then demolish the old one. lock_timeout is the foreman who sends the crane away if a truck blocks the lane, instead of halting the whole road to wait. The expand phase is the new bridge, the backfill is moving the parked cars, and the contract phase is the demolition.

Three common misunderstandings, up front ​

  1. "A fast migration is a safe migration." Duration of the work is not the risk. Duration of the wait for the lock is, because every later query queues behind the waiting ALTER. A one-millisecond change can freeze a table for as long as your longest open transaction.
  2. "ADD COLUMN rewrites the table." Not since PostgreSQL 11 for a nullable column or a non-volatile default. Only volatile defaults, stored generated columns and identity columns do.
  3. "CREATE INDEX CONCURRENTLY has no downside." It cannot run inside a transaction block, it takes longer, it waits for old transactions, and a failure leaves an INVALID index that still slows writes.

Where it comes from ​

The pieces of the answer come from different places. The first is the database manual: the ALTER TABLE page says which subforms take which lock and which rewrite the table, and it is the primary source for everything PostgreSQL on this page. The second is a software-design pattern. Danilo Sato's 2014 article on Martin Fowler's site describes it like this:

"Parallel change, also known as expand and contract, is a pattern to implement backward-incompatible changes to an interface in a safe manner, by breaking the change into three distinct phases: expand, migrate, and contract." — Danilo Sato, Parallel Change, martinfowler.com, 2014

The same article names the database case directly: "Most database refactorings follow the parallel change pattern, where the migrate phase is the transition period between the original and the new schema, until all database access code has been updated to work with the new schema." The third piece is tooling for engines that cannot do a change online by themselves. GitHub's gh-ost describes itself as "a triggerless online schema migration solution for MySQL", and Percona's pt-online-schema-change is a trigger-based tool in the same family.

PostgreSQL's own behaviour moved over time, which is why old advice misleads:

ReleaseChange that matters hereSource
PostgreSQL 11 (2018)"the ability to avoid a table rewrite for ALTER TABLE ... ADD COLUMN with a non-null column default"PostgreSQL 11 release notes
PostgreSQL 12 (2019)ALTER TABLE ... SET NOT NULL avoids the scan when a CHECK proves it; REINDEX CONCURRENTLYPostgreSQL 12 release notes
PostgreSQL 17 and latertransaction_timeout setting (documented in the current manual)Client Connection Defaults page
PostgreSQL 19 manual (current)Invalid not-null constraints: "If a column has an invalid not-null constraint, SET NOT NULL validates it"; virtual generated columns never need a rewritePostgreSQL 19 ALTER TABLE page
MySQL 8.0 and 8.4ALGORITHM=INSTANT for add column; "INSTANT is the default algorithm in MySQL 8.4"MySQL 8.4 Online DDL page

The concepts, one by one ​

Each block follows the same order: plain words, the usual wrong belief, the precise definition, a timeline, real scenarios, what each product does, and the fix. Code for the recipes is collected in Solving the classic problems.

The lock queue: why a quick ALTER stops the table Must-know ​

In plain words: your ALTER has to wait for everyone who is already using the table to finish. While it waits, everyone who arrives later waits behind it, even though they would not have conflicted with the old users.

Common misunderstanding: "My ALTER only waits for the other transaction; the rest of the app keeps going." No. PostgreSQL grants locks in queue order. A queued ACCESS EXCLUSIVE request conflicts with the ACCESS SHARE that a new SELECT wants, so the SELECT queues behind it. The pg_blocking_pids() of those new queries points at the ALTER, not at the old transaction.

Definition: a lock request is granted only if it does not conflict with granted locks and with earlier waiting requests. ACCESS EXCLUSIVE conflicts with every mode, so while it waits it blocks all new access to the table (a soft block), and once granted it blocks everything (a hard block). The same effect exists in MySQL as the metadata lock (MDL) queue: a DDL waiting for the metadata lock blocks later statements on that table.

A. No lock_timeoutB. lock_timeout = 2s + retrysession Xidle in transactionALTER TABLEwaits, no limitsession Xidle in transactionALTER TABLEgives up after 2sQueued behind the ALTER (blocked)SELECTINSERTUPDATESELECTSELECT... moreResult: the table looks down for as long assession X stays open. App pool exhausts,health checks fail, latency spikes.Needs: pg_blocking_pids, kill X, or wait.Everyone else keeps runningSELECTINSERTUPDATEERROR 55P03: canceling statement due tolock timeoutWrapper sleeps 0.5s, 1s, 1.5s ... and triesagain; the ALTER runs the moment no oldtransaction holds the table.Cost: a few failed attempts, no outage.
text
     S1 (report job)               S2 (migration)                       S3, S4 (application)
1    BEGIN;
2    SELECT count(*) FROM users;   -- ACCESS SHARE held; the transaction stays open
3                                  ALTER TABLE users ADD COLUMN note text;
4                                  -- wants ACCESS EXCLUSIVE: waits for S1
5                                                                       SELECT * FROM users WHERE id = 7;  -- waits behind S2
6                                                                       INSERT INTO users ...;             -- waits behind S2
7    -- 40 seconds later --
8    COMMIT;                       -- ALTER gets the lock, changes the catalog in ~1 ms, commits
9                                                                       -- S3 and S4 run; the table was "down" for 40 s

Real scenarios: a nightly report in a forgotten idle in transaction session; a long pg_dump or a COPY export holding ACCESS SHARE; an ORM request handler that opens a transaction, calls an external API, and commits a minute later; a deploy that runs migrations while a batch job is reading the table; a Laravel queue worker that keeps a transaction open during a slow HTTP call.

ProductWhat a waiting DDL does to later queries
PostgreSQLLater queries queue behind the waiting ALTER (fair lock queue); lock_timeout is the escape
MySQL InnoDBThe DDL waits for the metadata lock; later statements on the table queue behind it; lock_wait_timeout bounds the wait (pt-osc sets it to 60 s and innodb_lock_wait_timeout to 1 s so that it is the victim)
SQL ServerSchema-modification lock Sch-M queues like any lock; WAIT_AT_LOW_PRIORITY on online index operations lets the operation wait without blocking others
OracleDDL needs an exclusive DML lock; DDL_LOCK_TIMEOUT makes it wait for a period instead of failing at once (ORA-00054)
CockroachDBOnline schema changes run as background jobs and do not take a table-wide exclusive lock for the data change
SQLiteA schema change needs the single write lock; writers and sometimes readers get SQLITE_BUSY

Fix: bound the wait (SET lock_timeout), retry with back-off, and remove the old holders (idle_in_transaction_session_timeout, kill the stuck session) before the DDL runs. See lock_timeout and retry and the monitoring queries in Mechanics.

lock_timeout, statement_timeout and retry Must-know ​

In plain words: tell the database "if you cannot get this lock within two seconds, give up", then try again a bit later. A failed attempt costs nothing; a queued one can cost an outage.

Common misunderstanding: "statement_timeout is enough." It also kills a legitimate long step (an index build or a VALIDATE), and it does not distinguish waiting for a lock from doing work. The manual describes lock_timeout as aborting "any statement that waits longer than the specified amount of time while attempting to acquire a lock", and notes it "can only occur while waiting for locks". It also advises against setting it in postgresql.conf "because it would affect all sessions", so set it per session or per migration.

Definition: lock_timeout (milliseconds by default, 0 disables) cancels a statement that waits too long for any lock; the error is SQLSTATE 55P03 lock_not_available, message canceling statement due to lock timeout. The limit applies to each lock acquisition attempt separately. statement_timeout bounds total run time (SQLSTATE 57014). idle_in_transaction_session_timeout terminates sessions that sit in a transaction doing nothing, which removes the usual lock holders. transaction_timeout (PostgreSQL 17+) bounds whole transactions.

text
     Migration runner                              Database
1    SET lock_timeout = '2s';
2    ALTER TABLE users ADD COLUMN note text;       -- waits behind S1 ...
3                                                  ERROR 55P03: canceling statement due to lock timeout
4    sleep 0.5 s                                   -- queue drained, application runs normally
5    ALTER TABLE users ADD COLUMN note text;       -- waits ... 55P03 again
6    sleep 1.0 s
7    ALTER TABLE users ADD COLUMN note text;       -- S1 committed meanwhile: lock granted, 1 ms, done

Real scenarios: a migration job in the deploy pipeline that must never block the checkout path; a scheduled ADD CONSTRAINT at peak hour; a multi-tenant system where one schema's long report must not stop another's migration.

SettingApplies toWhere to set itTypical migration value
lock_timeoutPostgreSQL, any lock waitSET / SET LOCAL per session or transaction, or ALTER ROLE migrator SET lock_timeout1-5 s for metadata changes
statement_timeoutPostgreSQL, run timeper session0 for index builds, a few seconds for catalog changes
idle_in_transaction_session_timeoutPostgreSQL, idle sessionsrole or database level30-60 s on the application role
lock_wait_timeoutMySQL, metadata lockssession5-60 s
innodb_lock_wait_timeoutMySQL, row lockssessionthe tools set 1 s
DDL_LOCK_TIMEOUTOraclesessiona few seconds
WAIT_AT_LOW_PRIORITYSQL Server online index opsstatement optionMAX_DURATION in minutes

Fix: a retry wrapper that retries only on 55P03. Go and Laravel versions are in Retries and failure handling; the SQL part is one line.

sql
SET lock_timeout = '2s';             -- per session; use SET LOCAL inside a transaction
SET statement_timeout = '0';         -- index builds legitimately take long
ALTER TABLE users ADD COLUMN note text;   -- retry on SQLSTATE 55P03 with back-off

Rewrite or metadata-only Must-know ​

In plain words: some changes only edit the table's description in the catalog and finish at once. Others read every row and write a new copy of the table, which takes time proportional to its size and as much extra disk as the table itself.

Common misunderstanding: "Anything on a big table is slow, anything on a small table is fast." A metadata-only change on a billion-row table is instant; a rewrite of a million-row table already holds the lock for seconds. The manual gives the rewrite cases: adding a column with a volatile default (its example is clock_timestamp()), a stored generated column, an identity column, or a domain with constraints "will cause the entire table and its indexes to be rewritten", and changing a column's type "will normally cause the entire table and its indexes to be rewritten", with the exception that if the USING clause does not change the contents and the old type is binary coercible to the new type, no rewrite is needed (indexes are still rebuilt unless the system can show the new index is equivalent). A rewrite "may take a significant amount of time for a large table, and will temporarily require as much as double the disk space".

Definition: a table rewrite creates a new heap file (relfilenode) and copies every live row into it. A metadata-only change edits pg_attribute, pg_constraint and friends. You can tell which happened: SELECT relfilenode FROM pg_class WHERE relname = 'users'; before and after; a changed number means a rewrite.

text
     Session                                       Result
1    SELECT pg_relation_filenode('users');         -- 16452
2    ALTER TABLE users ADD COLUMN a int DEFAULT 7; -- constant default, PostgreSQL 11+
3    SELECT pg_relation_filenode('users');         -- 16452 (same file: metadata-only)
4    ALTER TABLE users ADD COLUMN b timestamptz DEFAULT clock_timestamp();
5    SELECT pg_relation_filenode('users');         -- 16466 (new file: full rewrite under ACCESS EXCLUSIVE)

Real scenarios: adding created_at DEFAULT now() is fast (now() is stable, evaluated once); adding uuid DEFAULT gen_random_uuid() is volatile and rewrites; int to bigint on an orders table rewrites for hours; widening varchar(100) to varchar(255) or to text does not.

ProductAdd columnChange typeDrop column
PostgreSQLMetadata-only unless volatile default / stored generated / identityRewrite unless binary coercibleMetadata-only, space reclaimed later
MySQL 8.4 InnoDBINSTANT (default algorithm when possible)COPY only (table rebuild, no concurrent DML) except extending VARCHAR in placeINSTANT in recent 8.0/8.4, otherwise INPLACE rebuild
SQL ServerMetadata-only for nullable or constant default (Enterprise and recent editions); otherwise size-of-dataSize-of-data operation; some changes can use the ONLINE option in recent versionsMetadata-only, space reclaimed on rebuild
OracleMetadata-only for NOT NULL with default since 11g; DBMS_REDEFINITION for the restOnline redefinitionSET UNUSED then drop later
SQLiteADD COLUMN is cheap; constraints on it are limitedNot supported: 12-step table rebuildDROP COLUMN supported since 3.35 (rewrites the table)
CockroachDBOnline schema change jobOnline, may backfill in the backgroundOnline job

Fix: treat every ALTER as "rewrite until proven otherwise", check the manual's "Notes" section, and verify with relfilenode on a copy.

Expand / migrate / contract (parallel change) Must-know ​

In plain words: instead of changing something in place, first add the new thing next to the old one (expand), move the application and the data over (migrate), and only then remove the old thing (contract). Every step is compatible with the one before it.

Common misunderstanding: "It is only one extra column; I can do it in one deploy." During a rolling deploy two versions of your code run at once, and during a rollback the old version runs against the new schema. A change that is correct only for new code against the new schema breaks one of those two moments.

Definition: Sato's pattern has three phases: expand (introduce the new interface alongside the old), migrate (move clients and data), contract (retire the old). For a database, the "interface" is the schema and the "clients" are every deployed application version, background job, report and replica consumer. The rule that makes it safe: every release must work against the schema as it was before the migration and as it will be after it.

Expand / migrate / contract across releasesD1 expandD2 dual-writeD3 read newD4 stop oldD5 contractSchema(migration)App readswhich columnApp writeswhich columnsDatabackfill, verifyold column onlynew column (fallback to old for unfilled rows until D4)old onlyold + new (dual write)new onlybackfill: id ranges, short batchesverify: no NULLs, VALIDATEDROP old columnold column + NEW nullable column (metadata only, lock_timeout)NOT VALID + VALIDATE, SET NOT NULL, INDEX CONCURRENTLY, drop old lastEvery release works with the schema before AND after it. Rollback of a release = redeploy the previous one;nothing is destroyed until D5.
text
     Deploy / job                                 Schema state                  Safe to roll back to?
1    D1  migration: ADD COLUMN display_name       old + new (new nullable)      yes (extra column is ignored)
2    D2  app: write BOTH columns                  old + new                     yes
3    --  job: backfill old rows in batches        old + new (new filling up)    yes
4    --  verify: no NULL left in display_name     old + new                     yes
5    D3  app: read display_name                   old + new                     yes (old column still current)
6    D4  app: stop writing full_name              old (stale) + new             yes to D3 only if flag still writes old
7    D5  migration: DROP COLUMN full_name         new only                      no: this is the point of no return

Real scenarios: rename a column; split full_name into first_name and last_name; change int to bigint; move a boolean to a status enum; turn a free-text field into a foreign key; change the unit of a money column from float to integer cents.

PhaseSchema changeApplication changeData workReversible?
ExpandAdd nullable column, table, index (concurrently)None, or ignore the new columnNoneYes, drop the new object
Migrate: dual writeNoneWrite old and newNoneYes
Migrate: backfillNoneNoneBatched copy of old rowsYes, rerun
Migrate: switch readsNoneRead new (flag)NoneYes, flip the flag
ContractConstraint, drop old columnRemove old code pathsNoneNo, from here roll forward

Fix: write the plan as a table of releases like the one above before writing any SQL, and make each row its own pull request. The Go and Laravel implementations of dual write are in Dual writes.

Dual writes Must-know ​

In plain words: for a while, every time the application saves the old column it also saves the new one, so that new data is correct in both places while old data is being copied over.

Common misunderstanding: "I can backfill first and add the dual write later." Rows written between the backfill and the dual-write deploy are missing the new value and nobody fills them. Dual write goes first; the backfill then fixes the past.

Definition: in the migrate phase the write path stores a value in both representations (old column and new column, or old table and new table) in the same transaction. Alternatives to application-level dual write are a database trigger (works for every writer including scripts and other services, costs write latency) and the shadow-table approach that pgroll and Reshape automate.

text
     Old app (D1)      New app (D2)     Backfill job         Row 41 state
1    writes full_name                                         full_name='Ann' display_name=NULL
2                      writes both                            (row 42 created by D2: both set)
3                                       UPDATE ... id 1-5000  display_name='Ann' (copied)
4    still running (rolling deploy)                           old app updates full_name='Anna' -> display_name stale!
5                                       second pass / trigger -> display_name='Anna'

Step 4 is the trap: while old instances still run, they update only the old column. Either finish the rollout of D2 before the backfill, or run the backfill (or a trigger) again after the last old instance is gone, and verify with a query such as SELECT count(*) FROM users WHERE display_name IS DISTINCT FROM full_name;.

Real scenarios: two services writing the same table, only one of which was updated; a bulk UPDATE in an admin script that bypasses the model layer (so an Eloquent saving hook never runs); an import job that uses INSERT ... ON CONFLICT raw SQL.

TechniqueCoversCost
Application dual write (model hook, repository)Code paths that go through itNone on the DB; misses raw SQL and other services
Database trigger BEFORE INSERT OR UPDATEEvery writerWrite latency, trigger must be dropped at contract time
Generated column (GENERATED ALWAYS AS ... STORED)Derived values onlyRewrite on add (PostgreSQL), so only for small tables
Tool-managed (pgroll, Reshape)Versioned views plus triggersAn extra tool and schema layer
Logical replication / CDC copyWhole-table movesOperational complexity; see Change Data Capture

Fix: the Go and Laravel dual-write code is in snippets; the SQL trigger version is below.

sql
-- Optional safety net: a trigger covers writers that bypass the application.
CREATE FUNCTION users_sync_display_name() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
    IF NEW.display_name IS NULL OR NEW.full_name IS DISTINCT FROM OLD.full_name THEN
        NEW.display_name := NEW.full_name;
    END IF;
    RETURN NEW;
END $$;

CREATE TRIGGER users_sync_display_name
    BEFORE INSERT OR UPDATE ON users
    FOR EACH ROW EXECUTE FUNCTION users_sync_display_name();
-- Creating a trigger takes SHARE ROW EXCLUSIVE: run it with lock_timeout and retry.
-- Drop it in the contract release.

Go (migrate phase, flag-controlled):

go
// Command dualwrite shows the migrate phase of expand/contract in application
// code: while the column rename full_name -> display_name is in flight, every
// write stores both columns and every read prefers the new one.
package main

import (
	"context"
	"database/sql"
	"fmt"
	"log"
	"os"

	_ "github.com/jackc/pgx/v5/stdlib"
)

// Flags come from configuration (environment, flag service). Each deploy
// flips exactly one of them, so a rollback is a flag flip, not a migration.
type Flags struct {
	WriteNewColumn bool // step 2: dual write
	ReadNewColumn  bool // step 4: read the new column first
}

type UserRepo struct {
	DB    *sql.DB
	Flags Flags
}

// SaveName writes the old column always, and the new one once dual writing is on.
func (r *UserRepo) SaveName(ctx context.Context, id int64, name string) error {
	if !r.Flags.WriteNewColumn {
		_, err := r.DB.ExecContext(ctx,
			`UPDATE users SET full_name = $2 WHERE id = $1`, id, name)
		return err
	}
	// One statement, so both columns change atomically in one transaction.
	_, err := r.DB.ExecContext(ctx,
		`UPDATE users SET full_name = $2, display_name = $2 WHERE id = $1`, id, name)
	return err
}

// Name reads the new column when it is trusted and falls back to the old one
// for rows the backfill has not reached yet.
func (r *UserRepo) Name(ctx context.Context, id int64) (string, error) {
	query := `SELECT full_name FROM users WHERE id = $1`
	if r.Flags.ReadNewColumn {
		query = `SELECT coalesce(display_name, full_name) FROM users WHERE id = $1`
	}
	var name string
	err := r.DB.QueryRowContext(ctx, query, id).Scan(&name)
	return name, err
}

func main() {
	url := os.Getenv("DATABASE_URL")
	if url == "" {
		fmt.Println("set DATABASE_URL to run this example")
		return
	}
	db, err := sql.Open("pgx", url)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	repo := &UserRepo{DB: db, Flags: Flags{WriteNewColumn: true}}
	if err := repo.SaveName(context.Background(), 1, "Ada"); err != nil {
		log.Fatal(err)
	}
	name, err := repo.Name(context.Background(), 1)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(name)
}

Laravel (Eloquent saving hook plus an accessor that prefers the new column):

php
<?php

// app/Models/User.php
// Migrate phase of expand/contract for the rename full_name -> display_name:
// every Eloquent write fills both columns, every read prefers the new one.
// Flip the two config flags one deploy at a time (config/migration.php).

namespace App\Models;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $fillable = ['full_name', 'display_name'];

    protected static function booted(): void
    {
        static::saving(function (User $user) {
            // Step 2, dual write. Eloquent only sends dirty attributes, so copy
            // explicitly. Bulk query-builder updates and raw SQL bypass this
            // hook: grep for them before you trust the backfill to be the last.
            if (config('migration.write_display_name') && $user->isDirty('full_name')) {
                $user->display_name = $user->full_name;
            }
        });
    }

    // Step 4, read the new column; fall back for rows not yet backfilled.
    protected function name(): Attribute
    {
        return Attribute::get(function (): ?string {
            if (config('migration.read_display_name')) {
                return $this->display_name ?? $this->full_name;
            }

            return $this->full_name;
        });
    }
}

Backfill in batches Must-know ​

In plain words: copy old data into the new column a few thousand rows at a time, each batch in its own short transaction, with a pause so the rest of the system can breathe.

Common misunderstanding: "One UPDATE users SET x = y is simplest and the database is built for it." In MVCC engines one huge UPDATE writes a new version of every row, holds row locks until commit, generates a burst of WAL that replicas must replay, and leaves millions of dead tuples for VACUUM. Details on why are in MVCC, VACUUM & Bloat.

Definition: a backfill walks the table by primary-key range (keyset, not OFFSET) and updates only rows that still need it (WHERE new_col IS NULL), which makes it idempotent and resumable. Typical batch: 1,000-10,000 rows, commit each, sleep or check replica lag between batches.

text
     Backfill worker                                   Effects
1    SELECT max(id) FROM users;                        -- 41,000,000
2    UPDATE users SET synced_at = coalesce(updated_at, created_at, now())
       WHERE id > 0 AND id <= 5000 AND synced_at IS NULL;   -- commit: ~5000 row versions
3    sleep 50 ms (or wait while replay_lag > 5 s)       -- replicas and autovacuum catch up
4    UPDATE ... WHERE id > 5000 AND id <= 10000 ...;    -- next range
5    crash / pause / deploy                             -- rerun: already-filled rows are skipped by IS NULL

Real scenarios: filling a new status column for 200 M orders; converting int ids to bigint ids; populating a denormalised counter; re-encrypting a column. The operational playbook for very large tables is in Billion-Row Tables; the batched-backfill diagram there is the same picture.

ChoiceOption AOption BWhen
Range walkWHERE id > $1 AND id <= $2WHERE id IN (SELECT ... LIMIT n FOR UPDATE SKIP LOCKED)A for dense integer keys; B for sparse or contended rows
Where it runsInside the deploy migrationQueue job / separate workerPrefer a job: pausable, rate-limited, not tied to the deploy timeout
ThrottleFixed sleepRead pg_stat_replication.replay_lag and waitLag-aware when replicas serve reads
ProgressLog rangesStore the last id in a tableStore it if the job can be restarted by someone else

Fix: Go and Laravel backfills are in the "after" snippets in Solving the classic problems.

Constraints in two steps: NOT VALID and VALIDATE Must-know ​

In plain words: adding a rule normally makes the database check every existing row while nobody can write. NOT VALID says "enforce it on new rows from now on, I will have you check the old rows later", and VALIDATE does that later check without blocking writes.

Common misunderstanding: "NOT VALID means the constraint is optional." It is enforced for every new insert and update at once. Only the old rows are unchecked until VALIDATE CONSTRAINT. Also, ADD CONSTRAINT ... NOT VALID still needs a brief ACCESS EXCLUSIVE (for CHECK) or SHARE ROW EXCLUSIVE (for a foreign key) to register itself, so it still needs lock_timeout.

Definition: the manual: "Normally, this form will cause a scan of the table to verify that all existing rows in the table satisfy the new constraint. But if the NOT VALID option is used, this potentially-lengthy scan is skipped. The constraint will still be applied against subsequent inserts or updates". VALIDATE CONSTRAINT "acquires only a SHARE UPDATE EXCLUSIVE lock on the table being altered" (and a ROW SHARE lock on the referenced table for a foreign key). Although most forms of ADD table_constraint need ACCESS EXCLUSIVE, ADD FOREIGN KEY needs only SHARE ROW EXCLUSIVE, on the referenced table as well.

text
     Migration                                              Lock held / effect
1    SET lock_timeout = '2s';
2    ALTER TABLE orders ADD CONSTRAINT orders_total_pos
       CHECK (total >= 0) NOT VALID;                        -- ACCESS EXCLUSIVE for milliseconds, no scan
3    -- new rows are checked from now on; old rows are not
4    ALTER TABLE orders VALIDATE CONSTRAINT orders_total_pos;
                                                            -- full scan, but SHARE UPDATE EXCLUSIVE: reads and writes continue
5    -- if an old row violates it: ERROR: check constraint "orders_total_pos" of relation "orders" is violated by some row
6    -- fix the rows in batches, run VALIDATE again

Real scenarios: CHECK (amount > 0) on a ledger; FOREIGN KEY (user_id) REFERENCES users on an events table with 2 billion rows; CHECK (status IN (...)) replacing an enum; a unique-ish rule with an exclusion constraint (build the supporting index first).

ConstraintPlain ADD lockWith NOT VALID then VALIDATE
CHECKACCESS EXCLUSIVE + full scanBrief ACCESS EXCLUSIVE; scan under SHARE UPDATE EXCLUSIVE
FOREIGN KEYSHARE ROW EXCLUSIVE on both tables + scanBrief SHARE ROW EXCLUSIVE; validate under SHARE UPDATE EXCLUSIVE (+ ROW SHARE on referenced)
UNIQUE / PRIMARY KEYBuilds an index, blocks writesNot supported with NOT VALID; use CREATE UNIQUE INDEX CONCURRENTLY then ADD CONSTRAINT ... USING INDEX
NOT NULLACCESS EXCLUSIVE + scanSee next block
EXCLUDEBuilds an index under a strong lockBuild the index concurrently where possible; no NOT VALID

Fix:

sql
SET lock_timeout = '2s';

ALTER TABLE orders ADD CONSTRAINT orders_total_pos CHECK (total >= 0) NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT orders_total_pos;

ALTER TABLE events
    ADD CONSTRAINT events_user_fk FOREIGN KEY (user_id) REFERENCES users (id) NOT VALID;
ALTER TABLE events VALIDATE CONSTRAINT events_user_fk;

-- A foreign key needs an index on the referencing column or deletes on users scan events:
CREATE INDEX CONCURRENTLY events_user_id_idx ON events (user_id);   -- own migration, no transaction

-- A unique constraint without a long write lock:
CREATE UNIQUE INDEX CONCURRENTLY users_email_uq ON users (email);
ALTER TABLE users ADD CONSTRAINT users_email_uq UNIQUE USING INDEX users_email_uq;  -- brief lock

Adding NOT NULL safely Must-know ​

In plain words: SET NOT NULL normally scans the whole table under a heavy lock to prove nobody is NULL. If you have already proven it with a CHECK that was validated without a heavy lock, PostgreSQL trusts that proof and skips the scan.

Common misunderstanding: "Add the column as NOT NULL DEFAULT x in one go." With a constant default that is fine on PostgreSQL 11+ (no rewrite), but with a volatile default, or when the value must be computed per row from other data, it rewrites the table or is impossible. And adding NOT NULL to an existing populated column always needs the verification scan unless a valid CHECK exists.

Definition: the manual for SET NOT NULL: it scans the table "unless NOT VALID is specified; however, if a valid CHECK constraint exists (and is not dropped in the same command) which proves no NULL can exist, then the table scan is skipped". This behaviour arrived in PostgreSQL 12 ("Allow ALTER TABLE ... SET NOT NULL to avoid unnecessary table scans", release notes). The current manual also describes invalid not-null constraints ("If a column has an invalid not-null constraint, SET NOT NULL validates it"), so on the newest releases there is a native route as well; the CHECK route works on every supported version since 12.

text
     Step                                                         Lock / effect
1    ALTER TABLE users ADD COLUMN synced_at timestamptz;          -- nullable: metadata only
2    app writes synced_at on every insert/update (dual write)
3    batched backfill until no NULL remains
4    ALTER TABLE users ADD CONSTRAINT users_synced_at_nn
       CHECK (synced_at IS NOT NULL) NOT VALID;                   -- brief ACCESS EXCLUSIVE
5    ALTER TABLE users VALIDATE CONSTRAINT users_synced_at_nn;    -- scan, SHARE UPDATE EXCLUSIVE
6    ALTER TABLE users ALTER COLUMN synced_at SET NOT NULL;       -- scan skipped (valid CHECK proves it)
7    ALTER TABLE users DROP CONSTRAINT users_synced_at_nn;        -- redundant now; brief lock

Real scenarios: making tenant_id mandatory after a backfill; enforcing email NOT NULL on a legacy table; tightening a column after a data clean-up.

RouteNeedsVersionNotes
Constant default on ADD COLUMNA constantPostgreSQL 11+One brief lock, no backfill needed
CHECK NOT VALID + VALIDATE + SET NOT NULLBackfill firstPostgreSQL 12+The portable route; this page's snippets use it
Native invalid not-null constraintBackfill firstRecent releases (current manual)Same idea in fewer steps; read your version's ALTER TABLE page
MySQL MODIFY col ... NOT NULLBackfill first8.xINPLACE, rebuilds the table, allows concurrent DML; fails in strict mode if NULLs remain
SQL Server ALTER COLUMN ... NOT NULLBackfill firstallSize-of-data operation on large tables

Fix: SQL above; Go and Laravel versions in the after snippets.

Indexes online: CREATE INDEX CONCURRENTLY, INVALID and REINDEX CONCURRENTLY Must-know ​

In plain words: a normal index build stops all writes to the table until it finishes. The CONCURRENTLY build lets writes continue by working in several passes, at the cost of taking longer and being able to fail halfway.

Common misunderstanding: "If CREATE INDEX CONCURRENTLY fails, nothing happened." It leaves behind an index marked INVALID. The planner ignores it, but every write still pays to maintain it. You must drop it (or REINDEX it) yourself.

Definition: the manual: "In a concurrent index build, the index is actually entered as an 'invalid' index into the system catalogs in one transaction, then two table scans occur in two more transactions. Before each table scan, the index build must wait for existing transactions that have modified the table to terminate. After the second scan, the index build must wait for any transactions that have a snapshot predating the second scan." It takes SHARE UPDATE EXCLUSIVE, so reads and writes continue, but only one concurrent build can run on a table at a time, and other schema changes on that table wait. It cannot run inside a transaction block (SQLSTATE 25001, message CREATE INDEX CONCURRENTLY cannot run inside a transaction block). A plain CREATE INDEX takes SHARE, which "locks out writes (but not reads)".

text
     Session A: CREATE INDEX CONCURRENTLY                  Session B: application writes
1    catalog: index entered as INVALID                      INSERT / UPDATE keep working
2    wait for transactions older than the first scan
3    scan 1: build the index from a snapshot                writes continue and are tracked
4    wait for transactions older than scan 2
5    scan 2: add rows changed during scan 1
6    wait for transactions with older snapshots
7    mark index VALID                                       planner can now use it
-- if step 3 or 5 fails (deadlock, uniqueness violation, cancel): index stays INVALID
sql
-- Find leftovers, including from REINDEX CONCURRENTLY (_ccnew / _ccold suffixes)
SELECT c.relname AS index, t.relname AS tbl
FROM pg_index i
JOIN pg_class c ON c.oid = i.indexrelid
JOIN pg_class t ON t.oid = i.indrelid
WHERE NOT i.indisvalid;

DROP INDEX CONCURRENTLY IF EXISTS users_synced_at_idx;          -- then try again
CREATE INDEX CONCURRENTLY users_synced_at_idx ON users (synced_at);

REINDEX INDEX CONCURRENTLY users_synced_at_idx;   -- PostgreSQL 12+: rebuild a bloated or invalid index online
-- If it fails it leaves *_ccnew (drop it and retry) or *_ccold (drop it; the rebuild itself worked).

Real scenarios: adding the index a new query needs on a hot table; replacing a bloated index; rebuilding after a failed concurrent build; swapping a unique index that backs a constraint; creating an index on a partitioned table (CREATE INDEX CONCURRENTLY is not supported on the partitioned parent: create ON ONLY the parent, build each partition's index concurrently, then ATTACH PARTITION the indexes).

OperationLockIn a transaction?Notes
CREATE INDEXSHAREYesBlocks writes for the whole build
CREATE INDEX CONCURRENTLYSHARE UPDATE EXCLUSIVENoTwo scans, waits for old transactions, may leave INVALID
DROP INDEXACCESS EXCLUSIVEYesBrief
DROP INDEX CONCURRENTLYWeaker locksNoUse for production indexes
REINDEX INDEX CONCURRENTLY (12+)SHARE UPDATE EXCLUSIVENoBuilds a new index and swaps; may leave _ccnew/_ccold
ALTER TABLE ... ADD ... USING INDEXBrief ACCESS EXCLUSIVEYesPromotes a prebuilt unique index to a constraint
MySQL ALTER TABLE ... ADD INDEXALGORITHM=INPLACE, LOCK=NONEImplicit commitConcurrent DML allowed
SQL Server CREATE INDEX ... WITH (ONLINE = ON)Online (edition dependent)n/aRESUMABLE = ON available in recent versions
Oracle CREATE INDEX ... ONLINEOnlinen/aDML allowed during the build

Fix: put CREATE INDEX CONCURRENTLY alone in its own migration, outside a transaction, with SET lock_timeout if a waiting DDL is a risk (the build waits for old transactions, it does not queue like ALTER), then check indisvalid afterwards. The Go and Laravel snippets drop and retry on failure.

Renames Important ​

In plain words: renaming a column or a table is a one-line, millisecond DDL, but the code that is running right now still uses the old name and will fail the instant the rename commits.

Common misunderstanding: "RENAME is metadata-only, so it is safe." It is cheap for the database and fatal for the application: old instances, background workers, reports, BI tools and ETL jobs all hold the old name.

Definition: RENAME COLUMN/RENAME TO take brief ACCESS EXCLUSIVE and no rewrite. Zero-downtime renames therefore do not rename; they add the new name next to the old and migrate (expand/contract), or put a compatibility layer in front: a view with the old name, or (PostgreSQL) a view with the new name over the table.

text
     Option A: two deploys (new column)                   Option B: view over a renamed table
1    ADD COLUMN display_name; dual write; backfill        ALTER TABLE users RENAME TO accounts;
2    switch reads to display_name                         CREATE VIEW users AS SELECT * FROM accounts;
3    stop writing full_name; later DROP COLUMN            -- old code keeps using "users" (a simple view is updatable)
4    -- no moment of incompatibility                      -- later: move code to "accounts", then DROP VIEW users

Real scenarios: renaming users.full_name to display_name; moving orders to sales_orders for a domain split; renaming a table that a reporting database reads through a foreign data wrapper.

TechniqueCostLimits
New column, dual write, backfillStorage and write cost for a whileWorks everywhere, including MySQL and logical replication
Rename table + compatibility viewAlmost freeSimple views are auto-updatable in PostgreSQL; rules and triggers needed otherwise; SELECT * views freeze their column list
Rename column + two deploys with old name kept via generated columnRewrite on add (stored)Only small tables
pgroll / Reshape versioned viewsTool setupPostgreSQL only; serves old and new schema from views

Fix: use option A for columns and option B only for tables. In Laravel, $table->renameColumn() on a hot table is the thing to avoid; add and migrate instead.

Column type changes (SET DATA TYPE) Important ​

In plain words: changing a column's type usually rewrites the whole table while it is locked. The safe way is to add a second column of the new type, copy into it gradually, and switch over.

Common misunderstanding: "ALTER COLUMN TYPE bigint is one statement, so it is one quick step." It is one statement that holds ACCESS EXCLUSIVE for the whole rewrite and rebuilds every index on the column. The classic outage is an int primary key about to overflow (2,147,483,647) on a table with hundreds of millions of rows.

Definition: the manual says changing the type "will normally cause the entire table and its indexes to be rewritten", except when the USING clause does not change the contents and the types are binary coercible. Examples that skip the rewrite are widening varchar(n) or converting it to text; whether a given conversion qualifies depends on the types, so verify with relfilenode (see Rewrite or metadata-only). The column's statistics are removed, so run ANALYZE afterwards.

text
     Step                                                          Notes
1    ADD COLUMN id_big bigint;                                      metadata-only
2    trigger or app dual write: id_big := id                        new rows covered
3    batched backfill: UPDATE ... SET id_big = id WHERE id BETWEEN  short transactions
4    CREATE UNIQUE INDEX CONCURRENTLY orders_id_big_uq ON orders (id_big);
5    ALTER TABLE orders ADD CONSTRAINT orders_id_big_nn CHECK (id_big IS NOT NULL) NOT VALID;
     VALIDATE CONSTRAINT; (then NOT NULL as in the previous block)
6    in ONE short transaction with lock_timeout:
       drop the old primary key constraint, ADD PRIMARY KEY USING INDEX orders_id_big_uq,
       rename id -> id_old, rename id_big -> id, fix defaults / sequences / foreign keys
7    later release: DROP COLUMN id_old

Real scenarios: int to bigint ids; float money to numeric or integer cents; timestamp to timestamptz; varchar(255) to text; text to jsonb; integer status to an enum or lookup table.

ChangePostgreSQLMySQL 8.4 InnoDB
varchar(n) to larger varchar or textNo rewriteINPLACE for extending VARCHAR within the same length-byte class; otherwise rebuild
int to bigintRewriteCOPY (rebuild, blocks DML): use gh-ost / pt-osc
timestamp to timestamptzRewrite in general (check your version and session time zone)COPY
text to jsonbRewrite with USINGCOPY
Anything with foreign keys pointing at the columnAll referencing columns must change tooForeign-key checks complicate online tools

Fix: expand/contract with a new column; on MySQL use gh-ost or pt-online-schema-change for the table copy instead.

Dropping columns, tables and indexes safely Important ​

In plain words: removing a column is quick for the database, but any code still reading or writing it will break. So you first make sure nothing uses it, and only then drop it.

Common misunderstanding: "DROP COLUMN frees the space and is irreversible only for the data; if the code is fine I can drop in the same deploy." The old application version that is still running during the deploy still names the column in its INSERT or SELECT list. Also, per the manual, DROP COLUMN "does not physically remove the column, but simply makes it invisible to SQL operations", so on-disk size does not shrink until the table is rewritten.

Definition: the safe order: (1) stop reading the column in code; (2) stop writing it and release that code everywhere; (3) wait one full deploy cycle plus any long-running jobs; (4) drop the column in its own migration with lock_timeout. For tables and indexes, check pg_stat_user_indexes.idx_scan over a full business cycle before dropping an index, and drop with DROP INDEX CONCURRENTLY.

The "ignore the column in the ORM first" idea comes from Rails: ActiveRecord caches column lists, so strong_migrations tells you to set self.ignored_columns and deploy before dropping (its README lists "Removing a column" among the operations it checks). Eloquent has no equivalent switch, because it does not cache a column list; it does select * unless told otherwise. In Laravel and Go the work is explicit: remove the attribute from $fillable, $casts, $appends, accessors and factories, grep for the column in query builder calls and raw SQL, remove it from Go struct tags and explicit SELECT lists (and stop using SELECT * into a struct that still has the field), and grep other services, BI tools and replicas.

text
     Release            Column "legacy_flag"                          Risk if skipped
1    R1  code stops reading it                                        none
2    R2  code stops writing it (INSERT/UPDATE lists)                  old R1 pods still insert it
3    --  wait: one deploy cycle, long jobs finish
4    R3  migration: DROP COLUMN legacy_flag (lock_timeout)            old R2 pods error: column does not exist
5    --  space stays until a table rewrite (VACUUM FULL / pg_repack / pg_squeeze or natural rewrite)

Real scenarios: retiring a feature flag column; removing PII columns after a policy change (the data is still in backups, see Backup, PITR & DR); dropping an unused index that wastes write throughput; dropping a table after a service migration.

ObjectDrop commandLockRewrite
Column (PostgreSQL)ALTER TABLE ... DROP COLUMNBrief ACCESS EXCLUSIVENo
Column (MySQL 8.4)ALTER TABLE ... DROP COLUMN, ALGORITHM=INSTANT where supported, else INPLACE rebuildBrief / concurrent DML allowedRebuild in the non-instant case
Index (PostgreSQL)DROP INDEX CONCURRENTLYWeakerNo
ConstraintALTER TABLE ... DROP CONSTRAINTBrief ACCESS EXCLUSIVENo (drops its index too)
TableDROP TABLEACCESS EXCLUSIVEn/a; rename it first and drop days later

Fix: a two-release removal and, for tables, "rename to _deprecated_<date>, wait, then drop".

Default values Important ​

In plain words: a default is a value the database fills in for new rows. Adding one to an existing column changes only future rows; adding a column with a default used to rewrite the table and, since PostgreSQL 11, usually does not.

Common misunderstanding: "SET DEFAULT also fills the existing rows." It does not. The manual says SET DEFAULT for a column applies to subsequent inserts only. And "PostgreSQL 11 made all defaults fast" is wrong: only non-volatile ones.

Definition: with a non-volatile default on ADD COLUMN, "the default value is evaluated at the time of the statement and the result stored in the table's metadata, where it will be returned when any existing rows are accessed", so the statement is "very fast even on large tables" (attmissingval in pg_attribute). A volatile default such as clock_timestamp(), random() or gen_random_uuid() is evaluated per row and forces a rewrite. now() and CURRENT_TIMESTAMP are stable, so they are evaluated once and are fast. PostgreSQL 11's release notes list "the ability to avoid a table rewrite for ALTER TABLE ... ADD COLUMN with a non-null column default".

text
     Statement                                                           Cost
1    ALTER TABLE t ADD COLUMN a int NOT NULL DEFAULT 0;                  fast (PostgreSQL 11+), brief ACCESS EXCLUSIVE
2    ALTER TABLE t ADD COLUMN b timestamptz DEFAULT now();               fast (stable function)
3    ALTER TABLE t ADD COLUMN c uuid DEFAULT gen_random_uuid();          REWRITE (volatile)
4    ALTER TABLE t ALTER COLUMN a SET DEFAULT 5;                         fast; only future rows
5    ALTER TABLE t ALTER COLUMN a DROP DEFAULT;                          fast

Real scenarios: status DEFAULT 'active' on a billion-row table (fast); public_id DEFAULT gen_random_uuid() (rewrite: add nullable, backfill in batches, then SET DEFAULT for future rows); created_at DEFAULT now().

ProductConstant default on add columnVolatile / expression default
PostgreSQL 11+Metadata-onlyRewrite
MySQL 8.4INSTANTINSTANT for constant defaults; check the Online DDL table for your version before relying on it for expression defaults
SQL ServerMetadata-only on recent editions for runtime constantsSize-of-data
Oracle 12c+Metadata-onlySize-of-data
SQLiteStored in the schema, applied on readNon-constant defaults not allowed on ADD COLUMN

Fix: nullable column, SET DEFAULT for new rows, backfill old rows, then constrain.

sql
ALTER TABLE users ADD COLUMN public_id uuid;                          -- metadata-only
ALTER TABLE users ALTER COLUMN public_id SET DEFAULT gen_random_uuid();   -- new rows only
-- backfill old rows in id ranges: UPDATE users SET public_id = gen_random_uuid() WHERE id > $1 AND id <= $2 AND public_id IS NULL;

Enum changes Good to know ​

In plain words: adding a value to a PostgreSQL enum is easy; removing or reordering values is not supported, so many teams avoid enums for values that change.

Common misunderstanding: "ALTER TYPE ... ADD VALUE is transactional like other DDL." The manual: "If ALTER TYPE ... ADD VALUE is executed inside a transaction block, the new value cannot be used until after the transaction has been committed." Older versions refused to run it in a transaction block at all, which is why migration frameworks offer a switch to turn the wrapping transaction off.

Definition: ALTER TYPE name ADD VALUE [IF NOT EXISTS] new_value [BEFORE|AFTER neighbor], and ALTER TYPE name RENAME VALUE existing TO new (a rename, no data change). There is no DROP VALUE. Comparisons involving a value added with BEFORE/AFTER "will sometimes be slower". In MySQL, "Modifying the definition of an ENUM or SET column" is INSTANT and metadata-only when you only append members at the end; reordering or removing members rebuilds the table.

text
     Session                                                          Result
1    BEGIN;
2    ALTER TYPE order_status ADD VALUE 'refunded';
3    UPDATE orders SET status = 'refunded' WHERE id = 1;              -- ERROR: unsafe use of new value "refunded" of enum type order_status
4    COMMIT;
5    UPDATE orders SET status = 'refunded' WHERE id = 1;              -- works after the commit

Real scenarios: adding a refunded state; renaming canceled to cancelled; removing an obsolete state (needs a type swap).

NeedPostgreSQL approachMySQL approach
Add a valueADD VALUE, use it only after commit; deploy code that writes it after the migrationAppend at the end: INSTANT
Rename a valueRENAME VALUE, but running code still sends the old name: add the new one, migrate, remove laterRebuild
Remove a valueCreate a new type, ALTER COLUMN TYPE ... USING status::text::new_type (rewrite): or use a new columnRebuild
Avoid the whole problemtext + CHECK (status IN (...)) added NOT VALID, or a lookup table with a foreign keySame

Fix: for values that change, use text with a CHECK ... NOT VALID or a lookup table; for a stable list an enum is fine. In migrations that add an enum value, make the migration file non-transactional, or run ADD VALUE in its own migration.

Large UPDATEs and DELETEs Must-know ​

In plain words: changing millions of rows in one statement is a migration too: it locks those rows, bloats the table and floods replicas.

Common misunderstanding: "It is only an UPDATE, not DDL, so it cannot take the site down." A single transaction that updates 100 million rows holds row locks until commit (blocking writers of those rows), writes at least 100 million new row versions, and its WAL must be shipped and replayed on every replica.

Definition: break the work into batches that each (a) touch a bounded number of rows, (b) commit, (c) can be retried and (d) are throttled. Also be aware of HOT updates (updating an indexed column prevents them and multiplies index writes), of autovacuum keeping up, and of table bloat afterwards (pg_repack or pg_squeeze can reclaim it without long locks; plain VACUUM FULL takes ACCESS EXCLUSIVE).

text
     One big UPDATE                                         Batched UPDATE (5,000 rows, sleep 50 ms)
1    BEGIN; UPDATE users SET ... ;  -- 100 M rows           for each id range:  UPDATE ... WHERE id > lo AND id <= hi AND col IS NULL; COMMIT;
2    row locks on all rows for the whole run                row locks for milliseconds
3    WAL burst; replica replay_lag grows to minutes         replay_lag stays seconds; reads from replicas stay fresh
4    100 M dead tuples for VACUUM at once                   autovacuum keeps pace between batches
5    one failure: whole thing rolls back                    one failure: rerun, filled rows are skipped

Real scenarios: backfilling a new column; archiving old rows (DELETE in batches, or detach a partition: ALTER TABLE ... DETACH PARTITION ... CONCURRENTLY); anonymising data after a policy change; fixing wrong data from a bug.

ConcernEffectMitigation
Row locks held too longWriters to the same rows waitSmall batches, short transactions
WAL volumeReplica lag, disk and archive growthThrottle on replay_lag; batch size down
Dead tuples / bloatSlow scans, index bloatPause for autovacuum; pg_repack later
Deadlocks between batch and app40P01Update in primary-key order; see Deadlocks
Triggers/foreign keys firing per rowSlower batchesDisable only with great care; or batch smaller

Fix: the snippets' backfills; use DETACH PARTITION ... CONCURRENTLY instead of mass DELETE when the data is partitioned by time (Partitioning & Sharding in PostgreSQL).

Migrations and replicas Important ​

In plain words: the replica runs the same DDL and the same data changes as the primary, in order, one at a time. A migration that is heavy on the primary is heavy on the replica too, and the replica can make it worse.

Common misunderstanding: "Replicas are read-only, so they are unaffected by what I run on the primary." Physical replication replays the primary's WAL, including its locks. The manual lists the conflict: "Access Exclusive locks taken on the primary server, including both explicit LOCK commands and various DDL actions, conflict with table accesses in standby queries." A long query on the standby then delays replay until max_standby_streaming_delay expires, after which the query is cancelled.

Definition: with streaming (physical) replication, DDL is replicated as WAL and the standby takes the corresponding ACCESS EXCLUSIVE lock when it replays it; it waits for conflicting standby queries, up to max_standby_streaming_delay, or cancels them. A rewrite or big backfill produces a WAL burst that increases replica lag (pg_stat_replication.replay_lag), so reads-after-write on replicas become stale. With logical replication, DDL is not replicated: the subscriber needs the schema change applied by you, in an order that keeps the publication working (add columns on the subscriber first, drop them there last). MySQL replicas apply the same ALTER from the binary log; a long ALTER blocks the replica's single applier thread (unless multi-threaded) and lag grows by the DDL's duration, which is why gh-ost is designed to read the binary log and --test-on-replica exists.

text
     Primary                                        Standby (hot_standby = on)
1    ALTER TABLE users ADD COLUMN x int;            -- WAL record: ACCESS EXCLUSIVE on users
2                                                   a long SELECT on users has been running for 2 min
3                                                   replay waits (conflict); replay_lag grows
4                                                   after max_standby_streaming_delay (default 30 s): the SELECT is cancelled
5                                                   replay continues; reads on the replica see x

Real scenarios: a reporting replica with 10-minute queries cancelled during a deploy; read-your-writes broken for a minute because a backfill made replay_lag jump; a logical replica to a data warehouse that stops because a column was dropped on the primary first.

SetupWhat the migration does therePrecaution
PostgreSQL streaming replica (hot standby)Replays DDL lock; may cancel long queriesShort DDL with lock_timeout; tune max_standby_streaming_delay for the window; avoid long queries during deploys
PostgreSQL logical replicationDDL not replicatedApply additive changes subscriber-first, destructive publisher-first (after the subscriber stopped using it)
MySQL async/semi-sync replicaReplays ALTER seriallyPrefer instant/in-place; use gh-ost with lag throttling
Read replicas behind a load balancerReads may hit a schema older or newer than the primary brieflyExpand first (new column ignored by old code), contract last
Standby promoted during a migrationHalf-applied backfillIdempotent batches; recheck with the verify query

Fix: lag-aware backfills (pg_stat_replication), additive changes first, and keep reports off the replica during the migration window. Failover and lag are taught in Replication, Read Replicas & Failover.

Transactional DDL: PostgreSQL versus MySQL implicit commit Must-know ​

In plain words: in PostgreSQL you can put several schema changes in one transaction and roll all of them back if something fails. In MySQL every DDL statement commits by itself, so a failed migration can leave you half-done.

Common misunderstanding: "My migration runs in a transaction, so a failure leaves nothing behind." True in PostgreSQL and SQL Server, false in MySQL (and Oracle). And even in PostgreSQL some statements cannot be in a transaction (CREATE INDEX CONCURRENTLY, REINDEX ... CONCURRENTLY, VACUUM), and wrapping a long multi-step migration in one transaction extends the ACCESS EXCLUSIVE lock from the first statement to the commit.

Definition: the MySQL manual lists the statements that cause an implicit commit: "Data definition language (DDL) statements that define or modify database objects", including ALTER TABLE, CREATE INDEX, DROP TABLE, RENAME TABLE, TRUNCATE TABLE. MySQL 8.0 and later make each individual DDL statement atomic ("atomic DDL ... combines the data dictionary updates, storage engine operations, and binary log updates into a single, atomic operation"), but a sequence of statements is still not one transaction, and the DDL commits any transaction already open. PostgreSQL DDL is transactional, with the lock held until commit.

text
     PostgreSQL                                               MySQL 8.4
1    BEGIN;                                                   START TRANSACTION;
2    ALTER TABLE a ADD COLUMN x int;                          ALTER TABLE a ADD COLUMN x int;   -- implicit COMMIT
3    ALTER TABLE b ADD COLUMN y int;   -- fails               ALTER TABLE b ADD COLUMN y int;   -- fails
4    ROLLBACK;  -- both undone, nothing changed               -- column x on a stays: half-applied
5    -- ACCESS EXCLUSIVE on "a" held from step 2 to step 4    -- migration tool marks the version "dirty"

Real scenarios: a Laravel migration with five Schema::table calls that fails on the fourth (PostgreSQL: all undone; MySQL: three applied); a golang-migrate "dirty" state after a MySQL failure; a CI check that applies migrations twice to prove idempotence.

ProductDDL in a transaction?Consequence for migration files
PostgreSQLYes (except CONCURRENTLY forms, VACUUM, CREATE DATABASE, ...)One file can be all-or-nothing; keep it short because of the lock
MySQL InnoDBNo: implicit commit; each statement atomic in 8.0+Keep one DDL per file/step; write idempotent steps (IF NOT EXISTS where available)
MariaDBNo: implicit commitSame as MySQL
SQL ServerYesAll-or-nothing possible
OracleNo: DDL commits implicitlyOne DDL per step
SQLiteYesAll-or-nothing; but table rebuilds are the norm
CockroachDBSchema changes in an explicit transaction are restricted; they run as jobsPrefer one schema change per transaction

Fix: for PostgreSQL, a transactional migration file that begins with SET LOCAL lock_timeout; for statements that cannot be transactional, a separate non-transactional step ($withinTransaction = false in Laravel, -- +goose NO TRANSACTION, a separate file for golang-migrate). For MySQL, one change per migration and idempotent guards.

Per-engine behaviour ​

Matrix 1: PostgreSQL ALTER TABLE forms and what they cost ​

Read from the PostgreSQL 19 ALTER TABLE page; lock names are the table-level modes from Locks & Concurrency. "Scan" means a full read of the table under that lock.

FormLockCostOnline alternative
ADD COLUMN nullable / constant defaultACCESS EXCLUSIVECatalog editnone needed
ADD COLUMN volatile default, identity, stored generated, constrained domainACCESS EXCLUSIVERewrite of table and indexesNullable + backfill
ADD COLUMN virtual generatedACCESS EXCLUSIVENever a rewrite (per the current manual)none needed
DROP COLUMNACCESS EXCLUSIVECatalog edit, space staysStop use first
RENAME COLUMN / RENAME TO / SET SCHEMAACCESS EXCLUSIVECatalog editTwo deploys, view
ALTER COLUMN TYPEACCESS EXCLUSIVERewrite unless binary coercible; indexes rebuilt; statistics droppedNew column
SET DEFAULT / DROP DEFAULTACCESS EXCLUSIVECatalog editnone needed
SET NOT NULLACCESS EXCLUSIVEScan, skipped if a valid CHECK proves itCHECK NOT VALID first
DROP NOT NULLACCESS EXCLUSIVECatalog editnone needed
ADD CHECKACCESS EXCLUSIVEScanNOT VALID + VALIDATE
VALIDATE CONSTRAINTSHARE UPDATE EXCLUSIVEScan, writes continuealready the online form
ADD FOREIGN KEYSHARE ROW EXCLUSIVE on both tablesScanNOT VALID + VALIDATE
ADD UNIQUE / PRIMARY KEYACCESS EXCLUSIVE while building the indexIndex build (and a scan for PRIMARY KEY nulls)CREATE UNIQUE INDEX CONCURRENTLY + USING INDEX
ADD UNIQUE/PRIMARY KEY ... USING INDEXACCESS EXCLUSIVE, briefCatalog edit; for a PRIMARY KEY whose columns are not already NOT NULL it also does SET NOT NULL, "a full table scan"the online form
ATTACH PARTITIONSHARE UPDATE EXCLUSIVE on parent, ACCESS EXCLUSIVE on the new partitionScan unless a matching CHECK already existsAdd the CHECK NOT VALID + VALIDATE first
DETACH PARTITION ... CONCURRENTLYWeaker, two transactionsNo rewritethe online form
SET TABLESPACE, SET LOGGED/UNLOGGEDACCESS EXCLUSIVERewrite / copyLogical replication or tools such as pg_repack
ENABLE/DISABLE TRIGGERSHARE ROW EXCLUSIVECatalog editnone needed
SET STATISTICS, SET (n_distinct ...)SHARE UPDATE EXCLUSIVECatalog editalready light
CREATE INDEXSHAREFull build, blocks writesCONCURRENTLY
CREATE INDEX CONCURRENTLYSHARE UPDATE EXCLUSIVETwo scans, waits for old transactionsthe online form
REINDEXBlocks writesRebuildREINDEX CONCURRENTLY (12+)

Matrix 2: MySQL 8.4 online DDL algorithms ​

MySQL lets each ALTER TABLE choose an ALGORITHM and a LOCK level, and fails fast if you ask for something the operation cannot do: ALGORITHM=INSTANT changes only metadata in the data dictionary, ALGORITHM=INPLACE works inside the storage engine (sometimes rebuilding the table in place) and usually permits concurrent DML, ALGORITHM=COPY creates a copy and blocks writes. The manual says that for adding a column "INSTANT is the default algorithm in MySQL 8.4". Values below are from Tables 17.15-17.17 of the Online DDL page (an asterisk in the manual means conditions apply, so read the notes for your version).

OperationINSTANTINPLACERebuilds tableConcurrent DML
Add columnYes*YesNo*Yes*
Drop columnYes*YesYesYes
Rename columnYes*YesNoYes*
Reorder columnsNoYesYesYes
Set column defaultYesYesNoYes
Change column data typeNoNoYes (COPY)No
Extend VARCHAR sizeNoYesNoYes
Make column NULLNoYesYes*Yes
Make column NOT NULLNoYes*Yes*Yes
Modify ENUM/SET definitionYesYesNoYes
Add secondary indexNoYesNoYes
Drop indexNoYesNoYes
Add primary keyNoYesYesYes
sql
-- Ask for exactly what you need; MySQL errors out instead of silently choosing a blocking path.
ALTER TABLE orders ADD COLUMN note varchar(100), ALGORITHM=INSTANT;
ALTER TABLE orders ADD INDEX idx_created (created_at), ALGORITHM=INPLACE, LOCK=NONE;
-- ERROR 1845 (0A000): ALGORITHM=INSTANT is not supported for this operation. Try ALGORITHM=COPY/INPLACE.
-- ERROR 1846 (0A000): ALGORITHM=INPLACE is not supported. Reason: ... Try ALGORITHM=COPY.

gh-ost and pt-online-schema-change ​

When MySQL cannot do the change online, a ghost-table tool does it for you. gh-ost is "a triggerless online schema migration solution for MySQL". It creates a ghost table with the new schema, copies rows in chunks, reads the binary log (from a replica or the primary) to apply concurrent changes, and swaps the tables at cut-over. Its own tips: "try out --test-on-replica first few times", issue a no-op first and then the real thing with --execute, use --postpone-cut-over-flag-file to control cut-over timing, and use the interactive commands to throttle or pause. pt-online-schema-change has the same shape but uses triggers on the original table, and its documentation says it "pauses the data copy operation if it observes any replicas that are delayed in replication" (--max-lag) and "pauses or aborts its operation if it detects too much load" (--max-load, --critical-load).

MySQL online schema change: ghost table, no downtimeordersold schema, live trafficreads + writes continue_orders_ghonew schema, rows copiedin chunks, then caught uporders (new schema)ghost renamed into placeold table kept or droppedbinary log streamgh-ost: no triggersrow copycut-overatomic RENAMErow changesControls and costsgh-ost: throttles on replica lag and load, can pause, postpone cut-over with a flag file, --test-on-replica.pt-online-schema-change: same shape, but triggers on the old table copy writes (more write cost on the primary).Needs about double the disk for the table, and the cut-over is the delicate moment; rehearse on a replica first.
ToolHow changes during the copy are capturedWrites costLag/load controlNotes
gh-ostBinary log stream, no triggersNo extra write path on the primaryThrottle on replica lag/load, pause, interactive commandsNeeds row-based binary logs (binlog_format=ROW, full row image); "Foreign key constraints are not supported" and "Triggers are not supported" (its requirements page); the old and new tables must share a PRIMARY KEY or other UNIQUE KEY
pt-online-schema-changeTriggers on the original tableEach write also runs a trigger--max-lag, --max-load, --critical-load; sets innodb_lock_wait_timeout=1, lock_wait_timeout=60Longer track record; supports more topologies
MySQL native online DDLOnline change log inside InnoDBRow log buffered (innodb_online_alter_log_max_size)NoneUse first when INSTANT/INPLACE, LOCK=NONE fits
Percona / MariaDB variantsSame familiesSameSameCheck engine-specific limits

What each database really does ​

ProductOnline schema change storyTransactional DDLNotable tooling
PostgreSQLFast catalog changes, NOT VALID/VALIDATE, CONCURRENTLY index and partition operations; no native "online rewrite" (type changes need new columns)Yes (except CONCURRENTLY)pgroll, Reshape, pg_repack, pg_squeeze, squawk, strong_migrations
MySQL 8.4 InnoDBNative online DDL with INSTANT/INPLACE/COPY; metadata locks queue like PostgreSQLNo (implicit commit; each statement atomic)gh-ost, pt-online-schema-change, strong_migrations
MariaDBOnline DDL similar to InnoDB's; ALGORITHM=INSTANT for add column since 10.3Nopt-osc; gh-ost works with caveats
SQL ServerMany operations metadata-only or online (ONLINE = ON, WAIT_AT_LOW_PRIORITY, resumable index operations in recent versions); Enterprise edition featuresYesRedgate/Flyway, DACPAC
OracleDBMS_REDEFINITION online redefinition; Edition-Based Redefinition lets old and new code see different editions of the schema, which is expand/contract built into the engine; DDL_LOCK_TIMEOUTNo (DDL commits)Liquibase, Flyway
SQLiteLimited ALTER TABLE (rename, add column, drop column since 3.35); anything else is the 12-step "create new table, copy, drop, rename" rebuild; one writer, so DDL blocks writersYesAtlas, golang-migrate, Laravel Schema
CockroachDBOnline schema changes run as background jobs: backfill while the table serves traffic; no table-wide lock for the backfillRestricted: schema changes inside multi-statement transactions have caveatsAtlas, golang-migrate
MongoDBNo schema to alter; the "migration" is a code concern: store a schemaVersion per document and migrate lazily on read/write or with a batch job; validation rules ($jsonSchema) can be tightened with validationLevel: moderate firstn/aapplication-level migrators
RedisNo schema; keys have implied shapes. Version the key prefix or the value format (user:v2:123), dual-write, then switch readersn/ascripts, SCAN-based migrators
Verification noteRows other than PostgreSQL and MySQL, and the version numbers for MariaDB INSTANT (10.3), SQLite DROP COLUMN (3.35), Oracle 11g/12c defaults, transaction_timeout (17) and the max_standby_streaming_delay default (30 s), are from vendor documentation and general knowledge, not from saved sources: check your release-

Mechanics ​

Watching the lock queue Must-know ​

While a migration runs (or seems stuck), these queries show who holds what, who waits, and who is the blocker. Lock modes are explained in Locks & Concurrency.

sql
-- 1. Sessions that hold locks while doing nothing: the usual culprits
SELECT pid, usename, state, now() - xact_start AS xact_age, left(query, 60) AS last_query
FROM pg_stat_activity
WHERE state = 'idle in transaction' AND xact_start < now() - interval '10 seconds'
ORDER BY xact_start;

-- 2. Who waits for what, and who blocks them (blocked sessions point at the ALTER, not the old holder)
SELECT a.pid, a.state, now() - a.query_start AS waiting_for,
       pg_blocking_pids(a.pid) AS blocked_by, left(a.query, 60) AS query
FROM pg_stat_activity a
WHERE cardinality(pg_blocking_pids(a.pid)) > 0;

-- 3. Ungranted lock requests on one table
SELECT l.pid, l.mode, l.granted
FROM pg_locks l
WHERE l.relation = 'users'::regclass AND NOT l.granted;

-- 4. Progress of CREATE INDEX / REINDEX
SELECT phase, blocks_done, blocks_total, tuples_done, tuples_total
FROM pg_stat_progress_create_index;

-- 5. Replica lag while backfilling
SELECT application_name, replay_lag, write_lag, flush_lag FROM pg_stat_replication;

-- 6. Indexes nobody uses (before dropping one) and indexes left INVALID
SELECT relname, indexrelname, idx_scan FROM pg_stat_user_indexes ORDER BY idx_scan;
SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid;
text
     Time   pid   state                 query                                    blocked_by
1    t0     101   idle in transaction   SELECT * FROM users                      {}
2    t0+1   202   active (waiting)      ALTER TABLE users ADD COLUMN ...         {101}
3    t0+2   303   active (waiting)      SELECT * FROM users WHERE id = 7         {202}
4    t0+2   304   active (waiting)      INSERT INTO users ...                    {202}
5    fix    -- SELECT pg_terminate_backend(101);  or wait for it; with lock_timeout, 202 cancels itself

MySQL equivalents: SHOW PROCESSLIST (state Waiting for table metadata lock), performance_schema.metadata_locks and performance_schema.data_lock_waits, sys.schema_table_lock_waits, and SHOW ENGINE INNODB STATUS for row locks.

Knobs Must-know ​

KnobProductWhat it doesMigration advice
lock_timeoutPostgreSQLCancels a lock wait (55P03)Always set per migration session
statement_timeoutPostgreSQLCancels long statements (57014)Short for catalog changes; 0 for index builds
idle_in_transaction_session_timeoutPostgreSQLTerminates idle transactionsSet on the application role so forgotten transactions cannot hold the queue
transaction_timeoutPostgreSQL 17+Bounds a whole transactionSafety net for long migration transactions
max_standby_streaming_delayPostgreSQL standbyHow long replay waits for conflicting queriesRaise only if reports matter more than lag
wal_compression, max_wal_sizePostgreSQLWAL volume and checkpointsWatch during rewrites and backfills
maintenance_work_mem, max_parallel_maintenance_workersPostgreSQLIndex build speedRaise for a big build, in that session only
lock_wait_timeoutMySQLMetadata-lock waitSet low for DDL (pt-osc sets 60 s)
innodb_lock_wait_timeoutMySQLRow-lock waitTools set 1 s so they lose conflicts
innodb_online_alter_log_max_sizeMySQLBuffer for concurrent DML during INPLACERaise for very busy tables, or the DDL fails
ALGORITHM, LOCK clausesMySQLDemand a specific online modeAlways spell them out
DDL_LOCK_TIMEOUTOracleDDL waits for the lockSet a few seconds
WAIT_AT_LOW_PRIORITYSQL ServerOnline index op yields to othersUse on online rebuilds

Error codes you will catch Must-know ​

CodeProductTextMeaningRetry?
55P03PostgreSQLcanceling statement due to lock timeoutlock_timeout firedYes, with back-off
57014PostgreSQLcanceling statement due to statement timeoutStatement too slowNo: raise the limit or batch
25001PostgreSQLCREATE INDEX CONCURRENTLY cannot run inside a transaction blockMigration wrapped in a transactionNo: make it non-transactional
40P01PostgreSQLdeadlock detectedA batch collided with the appYes, the batch only
23514PostgreSQLcheck constraint ... is violated by some rowVALIDATE found old bad rowsNo: fix the data, validate again
23503PostgreSQLinsert or update on table ... violates foreign key constraintOrphan rows at VALIDATENo: clean up, validate again
42701 / 42P07PostgreSQLcolumn ... already exists / relation ... already existsStep re-run after partial successTreat as done if the shape is right; use IF NOT EXISTS
55P04PostgreSQLunsafe use of new value ... of enum typeNew enum value used before commitNo: split transactions
1205MySQLLock wait timeout exceeded; try restarting transactionRow or metadata lock waitYes, with back-off
1213MySQLDeadlock found when trying to get lockDeadlockYes
1845 / 1846MySQLALGORITHM=... is not supportedOperation cannot use the requested algorithmNo: choose another or use gh-ost
1060 / 1061 / 1091MySQLduplicate column / key name / cannot dropRe-run after partial success (no transactional DDL)Guard the step
ORA-00054Oracleresource busy and acquire with NOWAIT specified or timeout expiredDDL could not get the lockYes; set DDL_LOCK_TIMEOUT

Tooling ​

Migration tools do three jobs: order the files, record what ran (a schema_migrations-style table), and run each file inside or outside a transaction. None of them makes a dangerous statement safe, so the safe-DDL rules above do not depend on the tool.

ToolLanguage / modelTransactionsLocking / concurrencyRollbackLinting
Laravel migrationsPHP, class per migration, up()/down()Per migration if the grammar supports it and $withinTransaction is true (MySQL grammar: no)migrate --isolated uses a cache lockmigrate:rollback runs down()migrate --pretend prints SQL
golang-migrateGo library and CLI, NNN_name.up.sql/.down.sqlPostgreSQL: multi-statement files run in a transaction; x-multi-statement flag; CREATE INDEX CONCURRENTLY needs its own fileAdvisory lock in the driverdown files, force to clear a dirty statenone built in
gooseGo library/CLI, SQL or Go migrationsDefault transaction per file; -- +goose NO TRANSACTION to skipLocking via the database-- +goose Downnone built in
AtlasDeclarative or versioned, HCL/SQL--tx-mode file (default), all, none; file directive also availableAdvisory locksDown migrations optionalatlas migrate lint (destructive and blocking-change analyzers)
sqitchPerl, plan file with deploy/revert/verify scripts per changePer script, you write BEGIN/COMMITDatabase-based registryrevert scriptsnone
FlywayJava, V1__name.sql versioned and R__ repeatableWraps each migration in a transaction by default; per-script .conf can turn it offSchema history table lockUndo migrations are a paid featureExternal linters
LiquibaseJava, XML/YAML/SQL changelogs of changesetsEach changeset a transaction by default; runInTransaction="false"DATABASECHANGELOGLOCKrollback blocks per changesetPolicy checks (Pro)
pgrollGo, JSON migrationsOwn multi-phase protocolShort locks, lock_timeout appliedpgroll rollback before completeoperations designed to avoid long locks
ReshapeRust, TOML migrationsOwn protocolShort locksreshape migration abortnone

The Go angle ​

database/sql is a pool, so SET lock_timeout is only reliable on a pinned *sql.Conn (or through the connection string, for instance pgx's options parameter, or a role-level ALTER ROLE migrator SET lock_timeout = '3s'). Every ExecContext on a *sql.Conn outside BeginTx is autocommit, which is what CREATE INDEX CONCURRENTLY requires. golang-migrate reads migrations from sources and applies them in order; as a CLI the README shows migrate -source file://path/to/migrations -database postgres://localhost:5432/database up 2, and as a library migrate.New(source, database) followed by m.Up() or m.Steps(n). Its PostgreSQL README warns about the multi-statement trap: running several statements in one Exec executes them inside a transaction, and "some statements can be only run outside of transaction (e.g. CREATE INDEX CONCURRENTLY)", so put such statements in separate files. The driver also takes x-statement-timeout (milliseconds), x-migrations-table, and x-multi-statement.

go
// Sketch: embedded migrations run at deploy time by a single leader.
// golang-migrate takes a lock in the database so two runners cannot overlap.
m, err := migrate.New("file://db/migrations",
	os.Getenv("DATABASE_URL")+"?x-statement-timeout=0&options=-c%20lock_timeout%3D3000")
if err != nil {
	log.Fatal(err)
}
if err := m.Up(); err != nil && !errors.Is(err, migrate.ErrNoChange) {
	log.Fatal(err) // a failed file leaves the version "dirty": fix by hand, then `migrate force N`
}

goose reads -- +goose Up / -- +goose Down annotations and wraps each file in a transaction unless it starts with -- +goose NO TRANSACTION; Atlas adds linting. A migration linter is simple enough to sketch with the standard library, and it makes a good CI gate while you adopt squawk or atlas migrate lint:

go
// Command lint is a tiny migration linter in the spirit of squawk and
// strong_migrations: it scans SQL migration files for statements that take a
// long ACCESS EXCLUSIVE lock or rewrite a table on PostgreSQL. It is a CI
// gate, not a parser; real projects should run squawk or atlas migrate lint.
package main

import (
	"bufio"
	"fmt"
	"os"
	"regexp"
	"strings"
)

type rule struct {
	name    string
	pattern *regexp.Regexp
	advice  string
}

var rules = []rule{
	{
		name:    "require-concurrent-index",
		pattern: regexp.MustCompile(`(?i)\bCREATE\s+(UNIQUE\s+)?INDEX\b`),
		advice:  "use CREATE INDEX CONCURRENTLY in its own migration, outside a transaction",
	},
	{
		name:    "constraint-missing-not-valid",
		pattern: regexp.MustCompile(`(?i)\bADD\s+CONSTRAINT\b.*\b(CHECK|FOREIGN\s+KEY)\b`),
		advice:  "add the constraint NOT VALID, then run VALIDATE CONSTRAINT in a later step",
	},
	{
		name:    "adding-not-null-field",
		pattern: regexp.MustCompile(`(?i)\bSET\s+NOT\s+NULL\b|\bADD\s+COLUMN\b.*\bNOT\s+NULL\b`),
		advice:  "add a CHECK (col IS NOT NULL) NOT VALID, validate it, then SET NOT NULL",
	},
	{
		name:    "volatile-default",
		pattern: regexp.MustCompile(`(?i)\bDEFAULT\s+(clock_timestamp|random|gen_random_uuid|uuid_generate_v4)\s*\(`),
		advice:  "a volatile default rewrites the table; add the column nullable and backfill in batches",
	},
	{
		name:    "changing-column-type",
		pattern: regexp.MustCompile(`(?i)\bALTER\s+COLUMN\b.*\b(SET\s+DATA\s+)?TYPE\b`),
		advice:  "most type changes rewrite the table; add a new column, dual-write, backfill, swap",
	},
	{
		name:    "ban-drop-column",
		pattern: regexp.MustCompile(`(?i)\bDROP\s+COLUMN\b`),
		advice:  "stop reading and writing the column in a previous release, then drop it",
	},
	{
		name:    "renaming-column",
		pattern: regexp.MustCompile(`(?i)\bRENAME\s+(COLUMN\s+)?\w+\s+TO\b`),
		advice:  "running code still uses the old name; add the new column and migrate in two deploys",
	},
}

var (
	timeoutSet = regexp.MustCompile(`(?i)\bSET\s+(LOCAL\s+)?lock_timeout\b`)
	lineNote   = regexp.MustCompile(`(?i)--\s*lint-ignore\s+([\w,-]+)`)
	alterTable = regexp.MustCompile(`(?i)^\s*ALTER\s+TABLE\b`)
)

func main() {
	if len(os.Args) < 2 {
		fmt.Fprintln(os.Stderr, "usage: lint migration.sql ...")
		os.Exit(2)
	}
	failed := false
	for _, path := range os.Args[1:] {
		problems, err := lintFile(path)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(2)
		}
		for _, p := range problems {
			fmt.Println(p)
			failed = true
		}
	}
	if failed {
		os.Exit(1)
	}
}

func lintFile(path string) ([]string, error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()

	var out []string
	sawTimeout := false
	sawDDL := false
	sc := bufio.NewScanner(f)
	for n := 1; sc.Scan(); n++ {
		line := sc.Text()
		if strings.HasPrefix(strings.TrimSpace(line), "--") && !lineNote.MatchString(line) {
			continue
		}
		if timeoutSet.MatchString(line) {
			sawTimeout = true
		}
		ignored := ""
		if m := lineNote.FindStringSubmatch(line); m != nil {
			ignored = strings.ToLower(m[1])
		}
		for _, r := range rules {
			if r.pattern.MatchString(line) && !strings.Contains(ignored, r.name) {
				if strings.Contains(strings.ToUpper(line), "NOT VALID") && r.name == "constraint-missing-not-valid" {
					continue
				}
				if strings.Contains(strings.ToUpper(line), "CONCURRENTLY") && r.name == "require-concurrent-index" {
					continue
				}
				sawDDL = true
				out = append(out, fmt.Sprintf("%s:%d: %s: %s", path, n, r.name, r.advice))
			}
		}
		if alterTable.MatchString(line) {
			sawDDL = true
		}
	}
	if sawDDL && !sawTimeout {
		out = append(out, fmt.Sprintf("%s:1: require-timeout-settings: SET lock_timeout before DDL so the lock queue cannot pile up", path))
	}
	return out, sc.Err()
}

The Laravel angle ​

By default each migration runs inside a transaction when the schema grammar supports transactional DDL: the framework's Migrator runs the callback inside $connection->transaction(...) only when supportsSchemaTransactions() is true and $migration->withinTransaction is true, and Migration declares public $withinTransaction = true; (this property is in the framework source, not on the migrations documentation page). Setting public $withinTransaction = false; is what makes CREATE INDEX CONCURRENTLY and ALTER TYPE ... ADD VALUE safe to use. php artisan migrate --pretend prints the SQL without running it, which is the cheapest review of what a migration will lock. With several servers deploying, php artisan migrate --isolated makes Laravel "acquire an atomic lock using your application's cache driver" so that only one runs (the default cache driver must be memcached, redis, dynamodb, database, file or array, and all servers must share the cache). migrate:rollback runs down(), which on a production table is almost never what you want (see Release strategy); schema:dump --prune squashes old migrations into a schema file for fast new-environment setup, but a squashed file is not for production. On MySQL, the schema builder offers an instant() column modifier ("nearly instantaneous regardless of table size", appended columns only) and a lock('none') modifier. Updating rows while paging is what chunkById is for: the queries documentation recommends it over chunk() when you "plan to update the retrieved records", because it paginates by primary key.

php
// Deploy order for a Laravel app (CI/CD step, before the new release takes traffic):
//   php artisan migrate --pretend --force      # review the SQL in the build log
//   php artisan migrate --isolated --force     # one runner, cache-locked
//   php artisan queue:restart                  # workers pick up new code and schema
// Long backfills are queued jobs (see BackfillSyncedAt), never part of `migrate`.

Versioned-view tools: pgroll and Reshape ​

Both automate expand/contract on PostgreSQL by serving two schema versions at once. pgroll "works by creating virtual schemas by using views on top of the physical tables"; for a breaking column change it "will create a new column in the physical schema, and backfill it from the old column", with triggers keeping the old and new column in sync. A migration is started (new schema version is available alongside the old), the application is rolled out against the new version, and then the migration is completed (old schema removed) or rolled back. Reshape works the same way: it works by "creating views that encapsulate the underlying tables" and sets up "triggers to translate inserts and updates between the old and new schema" with reshape migration start, complete and abort. The application must pick its schema version (for example by setting search_path), which is the price of the convenience.

Linters: squawk, atlas lint, strong_migrations ​

squawk lints PostgreSQL migration SQL in CI with rules such as require-concurrent-index-creation, ban-drop-column, adding-not-nullable-field and constraint-missing-not-valid, and can be silenced per statement with a squawk-ignore comment. atlas migrate lint analyses destructive and data-dependent changes. strong_migrations is the Rails gem the idea is named after: it "detects potentially dangerous operations", "prevents them from running by default" and "provides instructions on safer ways to do what you want", for PostgreSQL, MySQL and MariaDB. The ideas to copy into any stack: block the dangerous operation by default, explain the safe recipe in the error, require an explicit override with a reason, and check for missing lock_timeout.

Solving the classic problems ​

Each recipe is the sequence of releases, the SQL, then the Go and Laravel code for the preferred route.

ProblemPreferred solutionHowAdvantageCost or limitation
Add a NOT NULL column with a computed defaultExpand, backfill, CHECK NOT VALID, VALIDATE, SET NOT NULLSee belowNo long lockSeveral releases
Add a column with a constant defaultPlain ADD COLUMN ... DEFAULT (PostgreSQL 11+)One statement, lock_timeoutMetadata-onlyNot for volatile defaults
Rename a columnNew column, dual write, backfill, switch, dropRenamesNo outageExtra storage for a while
Change int to bigintNew column plus swap in one short transactionType changesNo long rewrite lockForeign keys must follow
Add a foreign keyNOT VALID then VALIDATEConstraintsWrites continueOrphans must be cleaned first
Add an indexCREATE INDEX CONCURRENTLYIndexesWrites continueSlower, may leave INVALID
Add a unique constraintUnique index concurrently + USING INDEXConstraintsBrief lockDuplicates must be removed first
Drop a columnStop use, release, dropDroppingSafe rollbacksWaits one cycle
Add an enum valueADD VALUE non-transactionallyEnumsInstantCannot remove values
Huge backfillBatches with lag throttleBackfillStable replicasTakes hours

Recipe: add a NOT NULL column to a huge table ​

The "before" migration is the classic outage: a volatile default, a plain index and one transaction with no timeout.

sql
-- Bad: a "one-shot" migration for a table with hundreds of millions of rows.
-- Everything below runs in one transaction under the migration tool.

-- clock_timestamp() is volatile, so PostgreSQL cannot store the default in the
-- catalog. It rewrites the whole table and its indexes while holding
-- ACCESS EXCLUSIVE; every read and write on users queues behind it.
ALTER TABLE users
    ADD COLUMN synced_at timestamptz NOT NULL DEFAULT clock_timestamp();

-- A plain CREATE INDEX blocks writes for the entire build, and it cannot even
-- run CONCURRENTLY inside this transaction.
CREATE INDEX users_synced_at_idx ON users (synced_at);

-- No lock_timeout: if one long transaction holds a lock on users, this DDL
-- waits for it, and every new query waits behind the DDL.

Go "after": the program pins a single connection with db.Conn so SET lock_timeout applies to every statement, retries only on SQLSTATE 55P03, backfills by id range with coalesce(updated_at, created_at, now()) so no NULL is left for VALIDATE, and builds the index outside a transaction.

go
// Command after runs an expand/contract migration against PostgreSQL with
// database/sql: each step is short, bounded by lock_timeout and retried.
package main

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"log"
	"os"
	"time"

	"github.com/jackc/pgx/v5/pgconn"
	_ "github.com/jackc/pgx/v5/stdlib"
)

const (
	lockTimeout = "3s"
	batchSize   = 5000
	maxAttempts = 10
)

func main() {
	ctx := context.Background()

	db, err := sql.Open("pgx", os.Getenv("DATABASE_URL"))
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// SET is per session, and *sql.DB is a pool. Pin one connection so that
	// lock_timeout applies to every statement below.
	conn, err := db.Conn(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	if _, err := conn.ExecContext(ctx, "SET lock_timeout = '"+lockTimeout+"'"); err != nil {
		log.Fatal(err)
	}

	// Phase 1, expand: a nullable column is a catalog-only change.
	// Deploy the application that dual-writes synced_at after this step.
	mustRetry(ctx, conn, "add column", stmt(`ALTER TABLE users ADD COLUMN IF NOT EXISTS synced_at timestamptz`))

	// Phase 2, migrate: backfill old rows in short transactions.
	if err := backfill(ctx, conn); err != nil {
		log.Fatal(err)
	}

	// Phase 3, contract: enforce NOT NULL without a long ACCESS EXCLUSIVE scan.
	// NOT VALID skips the table scan; the constraint applies to new writes only.
	mustRetry(ctx, conn, "add check", stmt(`ALTER TABLE users ADD CONSTRAINT users_synced_at_nn
		 CHECK (synced_at IS NOT NULL) NOT VALID`))
	// VALIDATE takes only SHARE UPDATE EXCLUSIVE, so writes keep flowing.
	mustRetry(ctx, conn, "validate check", stmt(`ALTER TABLE users VALIDATE CONSTRAINT users_synced_at_nn`))
	// With a valid CHECK proving no NULLs, SET NOT NULL skips its own scan.
	mustRetry(ctx, conn, "set not null", stmt(`ALTER TABLE users ALTER COLUMN synced_at SET NOT NULL`))
	mustRetry(ctx, conn, "drop check", stmt(`ALTER TABLE users DROP CONSTRAINT users_synced_at_nn`))

	// CONCURRENTLY cannot run inside a transaction block, and conn.ExecContext
	// is autocommit, so this is a standalone statement.
	mustRetry(ctx, conn, "create index", createIndex)
}

// backfill updates rows in id ranges. Every batch is its own transaction,
// so row locks are held for milliseconds and WAL and replicas keep up.
func backfill(ctx context.Context, conn *sql.Conn) error {
	var maxID int64
	if err := conn.QueryRowContext(ctx,
		`SELECT coalesce(max(id), 0) FROM users`).Scan(&maxID); err != nil {
		return err
	}

	for lo := int64(0); lo < maxID; lo += batchSize {
		hi := lo + batchSize
		res, err := conn.ExecContext(ctx,
			`UPDATE users SET synced_at = coalesce(updated_at, created_at, now())
			 WHERE id > $1 AND id <= $2 AND synced_at IS NULL`, lo, hi)
		if err != nil {
			return fmt.Errorf("batch (%d, %d]: %w", lo, hi, err)
		}
		n, _ := res.RowsAffected()
		log.Printf("backfilled (%d, %d]: %d rows", lo, hi, n)
		time.Sleep(50 * time.Millisecond) // let replicas and vacuum breathe
	}
	return nil
}

func createIndex(ctx context.Context, conn *sql.Conn) error {
	_, err := conn.ExecContext(ctx,
		`CREATE INDEX CONCURRENTLY IF NOT EXISTS users_synced_at_idx ON users (synced_at)`)
	if err != nil {
		// A failed concurrent build leaves an INVALID index behind; drop it
		// so the retry starts clean.
		_, _ = conn.ExecContext(ctx, `DROP INDEX CONCURRENTLY IF EXISTS users_synced_at_idx`)
	}
	return err
}

// stmt wraps a single SQL statement as a retryable step.
func stmt(query string) func(context.Context, *sql.Conn) error {
	return func(ctx context.Context, conn *sql.Conn) error {
		_, err := conn.ExecContext(ctx, query)
		return err
	}
}

// mustRetry runs a step and retries only on lock_timeout (SQLSTATE 55P03),
// backing off so that real traffic gets a window between attempts.
func mustRetry(ctx context.Context, conn *sql.Conn, name string,
	step func(context.Context, *sql.Conn) error) {
	for attempt := 1; ; attempt++ {
		err := step(ctx, conn)
		if err == nil {
			log.Printf("%s: ok", name)
			return
		}
		var pgErr *pgconn.PgError
		if !errors.As(err, &pgErr) || pgErr.Code != "55P03" || attempt == maxAttempts {
			log.Fatalf("%s: %v", name, err)
		}
		log.Printf("%s: lock_timeout, attempt %d/%d", name, attempt, maxAttempts)
		time.Sleep(time.Duration(attempt) * 500 * time.Millisecond)
	}
}

Laravel "before": a single migration with the same mistakes.

php
<?php

// database/migrations/2026_01_10_000000_add_synced_at_to_users.php
// Bad on a table with hundreds of millions of rows: one migration, one
// transaction (withinTransaction defaults to true), no lock_timeout.

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table) {
            // NOT NULL plus a volatile default: PostgreSQL rewrites the whole
            // table under ACCESS EXCLUSIVE while all traffic queues behind it.
            $table->timestampTz('synced_at')
                ->nullable(false)
                ->default(DB::raw('clock_timestamp()'));

            // A plain index build blocks writes until it finishes.
            $table->index('synced_at');
        });
    }

    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropIndex(['synced_at']);
            $table->dropColumn('synced_at');
        });
    }
};

Laravel "after", three steps shipped in order. The expand migration sets lock_timeout and $withinTransaction = false; a queued job backfills with chunkById; the contract migration adds the constraint NOT VALID, validates it, sets NOT NULL, and builds the index with CONCURRENTLY, retrying on lock timeouts.

php
<?php

// database/migrations/2026_01_10_000000_expand_users_synced_at.php
// Step 1, expand: a nullable column is a catalog-only change.

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    // Keep the session setting below on the same connection, and leave the
    // migration free to run statements that cannot live in a transaction.
    public $withinTransaction = false;

    public function up(): void
    {
        DB::statement("SET lock_timeout = '3s'");

        Schema::table('users', function (Blueprint $table) {
            $table->timestampTz('synced_at')->nullable();
        });

        // Deploy the application that writes synced_at on every create and
        // update (dual-write) before running the backfill job.
    }

    public function down(): void
    {
        DB::statement("SET lock_timeout = '3s'");

        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('synced_at');
        });
    }
};
php
<?php

// app/Jobs/BackfillSyncedAt.php
// Step 2, migrate: backfill old rows in short batches from a queue worker,
// outside any deploy-time migration.

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class BackfillSyncedAt implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable;

    public int $timeout = 3600;

    public function handle(): void
    {
        DB::table('users')
            ->whereNull('synced_at')
            // chunkById pages by primary key, so rows updated inside the
            // callback do not shift the next page (unlike plain chunk()).
            ->chunkById(5000, function (Collection $rows) {
                DB::table('users')
                    ->whereBetween('id', [$rows->first()->id, $rows->last()->id])
                    ->whereNull('synced_at')
                    ->update(['synced_at' => DB::raw('coalesce(updated_at, created_at, now())')]); // never leave NULLs behind, or step 3 fails

                usleep(50_000); // give replicas and autovacuum room
            }, 'id');
    }
}
php
<?php

// database/migrations/2026_01_20_000000_contract_users_synced_at.php
// Step 3, contract: enforce NOT NULL and build the index without long locks.

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

return new class extends Migration
{
    // CREATE INDEX CONCURRENTLY cannot run inside a transaction block.
    public $withinTransaction = false;

    public function up(): void
    {
        DB::statement("SET lock_timeout = '3s'");

        // NOT VALID: no table scan, enforced for new writes only.
        $this->retry(fn () => DB::statement(
            'ALTER TABLE users ADD CONSTRAINT users_synced_at_nn
             CHECK (synced_at IS NOT NULL) NOT VALID'
        ));

        // VALIDATE takes only SHARE UPDATE EXCLUSIVE; writes continue.
        $this->retry(fn () => DB::statement(
            'ALTER TABLE users VALIDATE CONSTRAINT users_synced_at_nn'
        ));

        // A valid CHECK proves there are no NULLs, so SET NOT NULL skips its scan.
        $this->retry(fn () => DB::statement(
            'ALTER TABLE users ALTER COLUMN synced_at SET NOT NULL'
        ));
        $this->retry(fn () => DB::statement(
            'ALTER TABLE users DROP CONSTRAINT users_synced_at_nn'
        ));

        $this->retry(function () {
            try {
                DB::statement(
                    'CREATE INDEX CONCURRENTLY IF NOT EXISTS users_synced_at_idx ON users (synced_at)'
                );
            } catch (\Throwable $e) {
                // A failed concurrent build leaves an INVALID index behind.
                DB::statement('DROP INDEX CONCURRENTLY IF EXISTS users_synced_at_idx');
                throw $e;
            }
        });
    }

    public function down(): void
    {
        DB::statement('DROP INDEX CONCURRENTLY IF EXISTS users_synced_at_idx');
        DB::statement('ALTER TABLE users ALTER COLUMN synced_at DROP NOT NULL');
    }

    /** Retry a DDL step when it gives up waiting for a lock (SQLSTATE 55P03). */
    private function retry(callable $step, int $attempts = 10): void
    {
        for ($i = 1; ; $i++) {
            try {
                $step();

                return;
            } catch (\Illuminate\Database\QueryException $e) {
                if ($e->getCode() !== '55P03' || $i >= $attempts) {
                    throw $e;
                }
                usleep($i * 500_000);
            }
        }
    }
};

Recipe: int to bigint on a hot table ​

sql
-- Release 1 (expand): metadata-only
SET lock_timeout = '3s';
ALTER TABLE orders ADD COLUMN id_big bigint;

-- Release 2: dual write. A trigger covers every writer.
CREATE FUNCTION orders_sync_id_big() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN NEW.id_big := NEW.id; RETURN NEW; END $$;
CREATE TRIGGER orders_sync_id_big BEFORE INSERT ON orders
    FOR EACH ROW EXECUTE FUNCTION orders_sync_id_big();

-- Job: backfill id ranges (UPDATE orders SET id_big = id WHERE id > $1 AND id <= $2 AND id_big IS NULL)

-- Release 3: index and constraint without long locks (each statement its own migration step)
CREATE UNIQUE INDEX CONCURRENTLY orders_id_big_uq ON orders (id_big);
ALTER TABLE orders ADD CONSTRAINT orders_id_big_nn CHECK (id_big IS NOT NULL) NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT orders_id_big_nn;
ALTER TABLE orders ALTER COLUMN id_big SET NOT NULL;   -- no scan: valid CHECK proves it

-- Release 4: the swap, one short transaction, lock_timeout, retried on 55P03.
-- Everything that still mentions id_big (trigger) or the old column (sequence default) moves here, atomically.
BEGIN;
SET LOCAL lock_timeout = '3s';
DROP TRIGGER orders_sync_id_big ON orders;                            -- its body assigns NEW.id_big, which is about to be renamed
ALTER TABLE orders DROP CONSTRAINT orders_pkey;                       -- also fix foreign keys that reference it
ALTER TABLE orders ADD CONSTRAINT orders_pkey PRIMARY KEY USING INDEX orders_id_big_uq;
ALTER TABLE orders RENAME COLUMN id TO id_old;
ALTER TABLE orders RENAME COLUMN id_big TO id;
ALTER SEQUENCE orders_id_seq AS bigint OWNED BY orders.id;            -- a serial sequence is integer-sized until you widen it
ALTER TABLE orders ALTER COLUMN id SET DEFAULT nextval('orders_id_seq');
ALTER TABLE orders ALTER COLUMN id_old DROP DEFAULT;
COMMIT;
-- Release 5 (later): ALTER TABLE orders DROP COLUMN id_old;

Foreign keys referencing orders.id must be recreated against the new column (NOT VALID, then VALIDATE) before the old primary key can be dropped; that is why this change is best scripted and rehearsed on a copy (Testing migrations).

Recipe: add a foreign key or unique constraint ​

The SQL is in Constraints in two steps. In Laravel the schema builder's foreign() emits a plain ADD CONSTRAINT, so use DB::statement for the NOT VALID form inside a non-transactional migration:

php
DB::statement("SET lock_timeout = '3s'");
DB::statement('ALTER TABLE events ADD CONSTRAINT events_user_fk
    FOREIGN KEY (user_id) REFERENCES users (id) NOT VALID');
DB::statement('ALTER TABLE events VALIDATE CONSTRAINT events_user_fk');

In Go the same two statements run on the pinned *sql.Conn through the mustRetry helper of the "after" program.

Recipe: ship the retry wrapper ​

See Retries and failure handling.

Release strategy: forward-only, flags and blue/green ​

In plain words: plan to move forward, not back. If a release goes wrong you redeploy the previous code (which still works with the schema) or flip a feature flag, you do not run down().

Common misunderstanding: "Every migration needs a working down() so that we can roll back." A down() that drops the new column destroys data written since the migration; one that restores the old shape cannot restore values users changed. Because expand steps only add things, the previous release keeps working against the expanded schema, which is the real rollback.

Definition: a forward-only strategy has these rules: (1) every release is compatible with the schema before and after it; (2) only expand steps ship in the same release as code that needs them; contract steps ship at least one release later; (3) a failed migration is repaired by a new migration, or by marking a step as applied after fixing by hand (migrate force, Flyway repair, Liquibase clearCheckSums); (4) behaviour switches are feature flags, not deploys.

text
     Timeline of a feature-flag-coordinated change
1    D1  migration: expand (add column)                      flags: write_new=off read_new=off
2    D2  code: dual write behind flag                        write_new=ON  (1% -> 100%)
3    --  backfill job runs; verify query = 0 rows differ
4    D3  code: read new behind flag                          read_new=ON   (canary, then all)
5    --  watch errors, p99, replica lag; flip read_new=OFF instantly if wrong
6    D4  code: remove old write and the flags
7    D5  migration: contract (drop old)                      point of no return
Migration pipeline with checks1 Pull requestSQL + app changeone concern each2 Lint (CI)squawk / atlas linttimeouts present?3 Dry run on copyprod-size datatime + lock + rewrite4 Apply expandlock_timeout + retryone runnerAny check failspipeline stops; prodkeeps the old schema5 Backfill jobbatches, sleep on lagpausable, resumable6 Verifyrun VALIDATEno NULLs, counts7 Deploy codeflag: read newwatch errors, p998 Contractlater release: dropold column / indexSignals watchedlock waits, replay_lag,error rate, WAL volumeRule: forward-only. A bad step is fixed by a new migration or a flag flip,never by running "down" on a table that already holds new data.
StrategyWhat it isSchema requirementRisk
Rolling deployInstances replaced one by one; old and new run togetherCompatible with both versionsTwo versions on one schema for minutes
Blue/greenTwo full environments, switch the routerOne shared database, so the schema must serve both coloursCut back to blue after a contract step = broken blue
CanaryA few instances get the new version firstSame as rollingNeeds flags for finer control
Feature flagsCode paths toggled at runtimeFlags only change behaviour, not schemaFlag debt: remove flags after contract
Schema versions side by side (pgroll, Reshape, Oracle editions)The engine/tool exposes old and new shapesTool-managedExtra moving parts
Maintenance windowStop writes, migrate, resumeNoneDowntime; still valid for tiny systems

Testing migrations on a copy ​

In plain words: before running a migration on production, run it on a recent copy of production, because the lock time, the rewrite and the data surprises all depend on real data.

Common misunderstanding: "It ran fine on staging." Staging has 10,000 rows and no long-running transactions, so it cannot show a rewrite that takes an hour, a VALIDATE that fails on one orphan row, or a lock queue.

text
     Step                                                                  What it proves
1    restore the latest backup or a snapshot clone to a scratch instance   realistic size and bloat
2    run migrations with the same flags as production                      duration, locks, rewrites (compare relfilenode)
3    replay recent production traffic or run a load generator in parallel  queue behaviour under load
4    run the verify queries (NULL counts, row counts, constraint validity) data correctness
5    run the migration a second time                                       idempotence
6    run the previous release's tests against the new schema               backward compatibility
7    for MySQL tools: gh-ost --test-on-replica                             cut-over and checksums
CheckWhereTool
Static lint (missing lock_timeout, blocking ALTER)CI on every pull requestsquawk, atlas migrate lint, the Go linter above
Dry run of SQLPre-deployphp artisan migrate --pretend, atlas migrate apply --dry-run
Rehearsal on a production-sized copyBefore first production runSnapshot restore, scratch instance
Compatibility testsCIRun previous release's suite against new schema
Post-deploy verificationAfter each stepVerify SQL, dashboards (lock waits, replay lag)

Retries and failure handling ​

Retry only what is safe to retry: a statement that gave up waiting for a lock changed nothing. Everything else needs a human or a new migration.

FailureMeaningRetry?Action
55P03 lock timeoutCould not get the lockYes, back-offRetry the same statement; alert after N attempts
40P01 / MySQL 1213DeadlockYesRetry the batch
57014 statement timeoutWork too slowNoSmaller batch or raise limit for this step
23514 / 23503 at VALIDATEOld rows violate ruleNoFix data in batches, validate again
Connection reset mid-stepUnknown resultCheck state firstQuery the catalog (information_schema.columns, pg_index.indisvalid); steps are idempotent (IF NOT EXISTS)
Dirty migration state (golang-migrate)A multi-statement file failed halfway (MySQL)NoInspect, fix by hand, migrate force N
INVALID indexCONCURRENTLY build failedAfter cleanupDROP INDEX CONCURRENTLY, retry

Rules that keep retries safe: every step is idempotent (ADD COLUMN IF NOT EXISTS, CREATE INDEX CONCURRENTLY IF NOT EXISTS after dropping an invalid one, WHERE col IS NULL in backfills), only one runner at a time (--isolated, advisory lock), a bounded number of attempts with growing back-off, and an alert when the bound is reached rather than an infinite loop. The Go helper mustRetry in the "after" program implements this for SQLSTATE 55P03; the Laravel retry() method in the contract migration does the same with QueryException::getCode() === '55P03'.

Choosing an approach ​

SituationRecommended approachExtra techniqueReason
Add nullable column, PostgreSQLPlain ADD COLUMNlock_timeout + retryMetadata-only
Add column with constant default, PostgreSQL 11+Plain ADD COLUMN ... DEFAULTlock_timeoutNo rewrite
Add column with volatile defaultNullable + backfill + SET DEFAULTBatches, then NOT NULL via CHECKAvoid the rewrite
Make existing column NOT NULLCHECK NOT VALID + VALIDATE + SET NOT NULLBackfill firstWeak lock instead of scan under a heavy one
Add CHECK / foreign keyNOT VALID + VALIDATEIndex on referencing columnWrites continue
Add index on busy tableCREATE INDEX CONCURRENTLYNon-transactional step, verify indisvalidWrites continue
Rebuild bloated indexREINDEX INDEX CONCURRENTLY (12+)Clean _ccnew leftoversOnline
Rename column/tableNew name, dual write, or a viewTwo deploysRunning code uses old name
Change typeNew column and swapTrigger dual writeAvoid long rewrite lock
Drop columnStop use, release, dropWait a deploy cycleOld code still names it
Enum valueADD VALUE, non-transactionalUse after commitInstant
MySQL add columnALGORITHM=INSTANTSpell it outFails fast if not instant
MySQL type change / big rebuildgh-ost or pt-online-schema-changeTest on replica, throttle on lagAvoids COPY blocking DML
PostgreSQL with many breaking changes and a platform teampgroll or ReshapeVersioned schemasAutomates expand/contract
Tiny database, nightly quiet periodPlain migration in a windowBackup firstSimplicity beats cleverness

In architecture: from a single process to a distributed system ​

Zero-downtime migration is a release-process decision more than an SQL one. It forces one rule: every application version must work against the schema before and after the migration, because during a rolling deploy both versions run at once. That is the property Sato says makes parallel change fit continuous delivery: it allows your code "to be released in any of these three phases".

Monolith: one process, one database ​

One deployable, one PostgreSQL. A Laravel app with a users table of 40 million rows wants to rename full_name to display_name. Release 1: migration adds display_name nullable (with lock_timeout, --isolated), the User model dual-writes. A queued job backfills with chunkById. Release 2: read display_name. Release 3: stop writing full_name. Release 4: contract migration drops it. Even here, the web workers, the queue workers and the scheduler are three "services" running different code versions during a deploy, so the rule already applies.

Modular monolith and multiple databases ​

Several modules share one database but own different tables, or each module has its own schema or database. The module that owns a table is the only one allowed to migrate it, and other modules must not read its columns directly (use the module's API or a view). A migration that changes an owned table's shape publishes the change as a view or an interface, so consumers migrate on their own schedule. Cross-module foreign keys make VALIDATE and index builds interact: plan them as one change with one owner. Tools matter: a single linear migration history per database is simple, but module-owned migration directories need an ordering rule (timestamps plus a module prefix).

Microservices: each service owns its schema, contracts cross services ​

Each service owns its database and migrates it alone, so a schema change never blocks another service's deploy. What crosses the boundary is the contract: API payloads and events. Changing a column that appears in an event or response means expand/contract on the contract as well: publish both fields, migrate consumers, retire the old field (Message Design & Schema Evolution). A multi-service example: billing renames amount to amount_minor (integer cents).

text
     Service            Step                                                       Compatibility
1    billing  D1        add amount_minor nullable; dual write amount + amount_minor   consumers unaffected
2    billing  job       backfill amount_minor in batches                              consumers unaffected
3    billing  D2        events carry both "amount" and "amount_minor"                 old consumers read amount
4    invoicing D1       reads amount_minor, falls back to amount                      both producers' versions work
5    billing  D3        stop sending "amount" after all consumers confirmed           contract on the event
6    billing  D4        drop column amount                                            point of no return

Backfills in a service that also publishes change events through an outbox must not emit a flood of events: mark backfill updates as silent or update a column that is not part of the event (Transactional Outbox Pattern). Change data capture consumers see the new column and need their own schema step (Change Data Capture).

Distributed data: replicas, caches and multi-region ​

Read replicas lag and replay DDL locks (see Migrations and replicas). Caches hold serialised objects shaped by the old schema: a new column the old cached object lacks, or a removed one the new code expects, needs versioned cache keys (user:v2:123) or tolerant readers, and a cache flush at contract time is a stampede risk. Search indexes and warehouses fed by CDC need the column added downstream before the producer starts writing it, and dropped downstream last. Multi-region and distributed SQL (CockroachDB, Spanner) run schema changes as online background jobs: they remove the lock queue problem but not the compatibility problem, because every application version across regions still has to work with both schemas during the job. Sharded setups (Citus, application sharding) multiply everything by the number of shards: migrate one shard first as a canary, then roll across, with the same step discipline (Partitioning & Sharding in PostgreSQL).

Scaling path: 1x, 10x, 100x ​

ScaleTable size and trafficApproach
1xThousands to millions of rows, quiet periodsPlain migrations with lock_timeout; a maintenance window is acceptable
10xTens of millions of rows, constant trafficExpand/contract by habit; CONCURRENTLY always; NOT VALID always; batched backfills as jobs; CI lint
100xBillions of rows, replicas, many servicesTool-assisted (gh-ost, pgroll), rehearsals on production-sized copies, lag-aware backfills, migration review as a ritual, partitioning to make drops and archival cheap (Billion-Row Tables)
BeyondMulti-region, many tenants, thousands of tablesPlatform team owns the pipeline; per-tenant/shard rollouts with canaries and automatic abort on lag or error rate

Lab ​

Two terminals per experiment, PostgreSQL 17. Expected output is in comments; error texts are the ones the PostgreSQL manual prints. The lab was not executed on the authoring machine (no database was available), so compare the output with your own run and trust your run.

Setup.

bash
docker run -d --name pg -e POSTGRES_PASSWORD=pg -p 5432:5432 postgres:17
# terminals A, B, C:  docker exec -it pg psql -U postgres
sql
CREATE TABLE users (
    id         bigserial PRIMARY KEY,
    email      text NOT NULL,
    full_name  text,
    created_at timestamptz NOT NULL DEFAULT now(),
    updated_at timestamptz
);
INSERT INTO users (email, full_name, updated_at)
SELECT 'u' || g || '@example.com', 'User ' || g, now() FROM generate_series(1, 200000) g;

Experiment 1: a blocking ALTER and the queue behind it.

text
     A (old transaction)               B (migration)                          C (application)
1    BEGIN;
2    SELECT count(*) FROM users;       -- 200000
3                                      ALTER TABLE users ADD COLUMN note text;
4                                      -- hangs: waits for ACCESS EXCLUSIVE
5                                                                             SELECT 1 FROM users LIMIT 1;   -- hangs too
6    -- in a fourth terminal:
     SELECT pid, pg_blocking_pids(pid), left(query, 40) FROM pg_stat_activity WHERE cardinality(pg_blocking_pids(pid)) > 0;
     -- B is blocked by A's pid; C is blocked by B's pid (not A's)
7    COMMIT;                           -- B finishes in milliseconds, C returns at once

Experiment 2: the same migration with lock_timeout.

text
     A                                 B
1    BEGIN; SELECT count(*) FROM users;
2                                      SET lock_timeout = '2s';
3                                      ALTER TABLE users ADD COLUMN note2 text;
4                                      -- after 2 s: ERROR:  canceling statement due to lock timeout   (SQLSTATE 55P03)
5                                      SELECT 1 FROM users LIMIT 1;   -- C (or B itself) is not blocked any more
6    COMMIT;
7                                      ALTER TABLE users ADD COLUMN note2 text;   -- retry succeeds immediately

Experiment 3: NOT VALID still needs a brief lock, and VALIDATE does not block writes.

text
     A (old transaction)                         B (migration)                                        C (writer)
1    BEGIN; SELECT count(*) FROM users;
2                                                SET lock_timeout = '2s';
3                                                ALTER TABLE users ADD CONSTRAINT users_email_chk
                                                   CHECK (email LIKE '%@%') NOT VALID;
4                                                -- 2 s later: ERROR:  canceling statement due to lock timeout
5                                                -- NOT VALID removed the scan, not the lock: A still blocks it
6    COMMIT;
7                                                ALTER TABLE users ADD CONSTRAINT users_email_chk
                                                   CHECK (email LIKE '%@%') NOT VALID;   -- ALTER TABLE, instantly
8                                                ALTER TABLE users VALIDATE CONSTRAINT users_email_chk;
9                                                                                                      -- while step 8 runs:
                                                                                                      UPDATE users SET updated_at = now() WHERE id = 1;  -- not blocked

Experiment 4: rewrite versus metadata-only.

sql
SELECT pg_relation_filenode('users');                                  -- e.g. 16452
ALTER TABLE users ADD COLUMN a int NOT NULL DEFAULT 7;                  -- fast
SELECT pg_relation_filenode('users');                                  -- 16452: same file, no rewrite
ALTER TABLE users ADD COLUMN b timestamptz DEFAULT clock_timestamp();   -- volatile: rewrites 200,000 rows
SELECT pg_relation_filenode('users');                                  -- different number: new file

Experiment 5: the safe NOT NULL, and a failed concurrent index.

sql
ALTER TABLE users ADD COLUMN synced_at timestamptz;                      -- nullable
UPDATE users SET synced_at = coalesce(updated_at, created_at) WHERE id <= 100000;   -- batch 1
UPDATE users SET synced_at = coalesce(updated_at, created_at) WHERE id > 100000;    -- batch 2
ALTER TABLE users ADD CONSTRAINT users_synced_at_nn CHECK (synced_at IS NOT NULL) NOT VALID;
ALTER TABLE users VALIDATE CONSTRAINT users_synced_at_nn;
ALTER TABLE users ALTER COLUMN synced_at SET NOT NULL;                   -- no scan
ALTER TABLE users DROP CONSTRAINT users_synced_at_nn;

-- A failed concurrent build leaves an INVALID index: make a duplicate and try a unique index
INSERT INTO users (email, full_name, synced_at) VALUES ('dup@example.com', 'A', now()), ('dup@example.com', 'B', now());
CREATE UNIQUE INDEX CONCURRENTLY users_email_uq ON users (email);
-- ERROR:  could not create unique index "users_email_uq"
-- DETAIL:  Key (email)=(dup@example.com) is duplicated.
SELECT indexrelid::regclass, indisvalid FROM pg_index WHERE NOT indisvalid;   -- users_email_uq | f
\d users                                                                      -- shows: "users_email_uq" UNIQUE, btree (email) INVALID
DROP INDEX CONCURRENTLY users_email_uq;
DELETE FROM users WHERE full_name = 'B';
CREATE UNIQUE INDEX CONCURRENTLY users_email_uq ON users (email);            -- succeeds
BEGIN; CREATE INDEX CONCURRENTLY x ON users (full_name); ROLLBACK;
-- ERROR:  CREATE INDEX CONCURRENTLY cannot run inside a transaction block

Experiment 6 (optional): the linter. cd docs/snippets/database/schema-migrations/go && go run ./lint before/001_add_synced_at.sql prints four findings (not-null, volatile default, non-concurrent index, missing lock_timeout) and exits 1.

Common misconceptions ​

BeliefReality
"A fast ALTER is a safe ALTER"The wait for the lock is the risk; later queries queue behind the waiting ALTER
"ADD COLUMN rewrites the table"Not since PostgreSQL 11 for nullable or constant defaults; only volatile, stored generated or identity
"NOT VALID means unenforced"New writes are checked at once; only old rows wait for VALIDATE; it still needs a brief lock
"CONCURRENTLY cannot fail"It leaves an INVALID index that costs write overhead; drop and retry
"Wrap the migration in a transaction and it is atomic everywhere"MySQL and Oracle commit DDL implicitly; PostgreSQL cannot put CONCURRENTLY in a transaction
"RENAME is instant, so it is safe"The database is fine; the running code is not
"DROP COLUMN reclaims disk"It only hides the column; space returns on rewrite
"SET DEFAULT fills existing rows"It affects future inserts only
"Rollback means down()"Forward-only: redeploy the previous release or flip a flag
"Replicas ignore my migration"They replay the lock and the WAL; long standby queries get cancelled and lag grows
"It worked on staging"Staging cannot show size, bloat, long transactions or lag
"One big UPDATE is fine because it is not DDL"It bloats, floods WAL and holds row locks; batch it
"lock_timeout in postgresql.conf is the fix"The manual advises against it: set it per migration session

Cheat sheet ​

TopicWhat to remember
Start of every migrationSET lock_timeout = '2s'; retry on 55P03 with back-off
Cheap on PostgreSQLNullable or constant-default ADD COLUMN, DROP COLUMN, RENAME, SET DEFAULT (all brief ACCESS EXCLUSIVE)
RewritesVolatile default, stored generated, identity, most type changes
Detect a rewritepg_relation_filenode before and after
ConstraintsADD ... NOT VALID then VALIDATE CONSTRAINT (SHARE UPDATE EXCLUSIVE)
NOT NULLBackfill, CHECK ... NOT VALID, VALIDATE, SET NOT NULL (scan skipped, PostgreSQL 12+), drop the CHECK
IndexesCREATE INDEX CONCURRENTLY alone, no transaction; check indisvalid; REINDEX ... CONCURRENTLY
Unique constraintUnique index concurrently, then ADD CONSTRAINT ... USING INDEX
Rename / type changeNew column, dual write first, backfill, switch reads, drop last
BackfillId ranges, short transactions, WHERE new IS NULL, sleep on replay_lag
DropStop reading, stop writing, wait, then drop
EnumADD VALUE outside a transaction (or do not use the value in it)
MySQLSpell out ALGORITHM=INSTANT/INPLACE and LOCK=NONE; gh-ost/pt-osc for the rest; DDL commits implicitly
Laravel$withinTransaction = false, migrate --pretend, --isolated, chunkById jobs
GoPin a *sql.Conn for SET; golang-migrate multi-statement trap; goose NO TRANSACTION; Atlas --tx-mode
ProcessLint in CI, rehearse on a copy, forward-only, flags, contract one release later

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A migration that adds a nullable column "only takes a millisecond" yet the site froze for 40 seconds. What happened? Must-know ​

Answer

Answer: The ALTER needed ACCESS EXCLUSIVE, waited for an old transaction holding ACCESS SHARE, and every later query queued behind the waiting ALTER. The cure is lock_timeout plus retry, and removing idle-in-transaction sessions. See The lock queue.

2 — Why is lock_timeout better than statement_timeout for a migration step, and where should you set it? Important ​

Answer

Answer: lock_timeout only fires while waiting for a lock, so it does not kill a legitimately long step such as an index build; the manual recommends against setting it in postgresql.conf because it affects all sessions, so set it per session or role for the migration. See lock_timeout and retry.

3 — Which of these rewrite the table in PostgreSQL 11 or later: ADD COLUMN a int DEFAULT 0, ADD COLUMN b uuid DEFAULT gen_random_uuid(), ALTER COLUMN c TYPE bigint, DROP COLUMN d? How can you verify? Important ​

Answer

Answer: The second (volatile default) and the third (type change) do; the first is stored in the catalog and DROP COLUMN only hides the column. Compare pg_relation_filenode() before and after. See Rewrite or metadata-only.

4 — Describe the six steps to rename a column without downtime. Must-know ​

Answer

Answer: Add the new column nullable; deploy code that writes both; backfill old rows in batches; verify; deploy code that reads the new column; stop writing the old one and drop it in a later release. See Expand / migrate / contract and Renames.

5 — Why must dual writes go live before the backfill starts? Important ​

Answer

Answer: Rows written between the backfill and the dual-write deploy would be missing the new value and nobody would fill them. The backfill fixes the past; dual write covers the future. Also re-run or verify after the last old instance is gone. See Dual writes.

6 — What does ADD CONSTRAINT ... NOT VALID skip, what does it still need, and what does VALIDATE CONSTRAINT lock? Important ​

Answer

Answer: It skips the table scan and enforces the rule only for new rows, but it still needs a brief ACCESS EXCLUSIVE (SHARE ROW EXCLUSIVE for a foreign key) and so still needs lock_timeout. VALIDATE scans under SHARE UPDATE EXCLUSIVE, which lets reads and writes continue. See Constraints in two steps.

7 — Give the safe sequence for adding NOT NULL to a populated column on PostgreSQL 12 or later. Must-know ​

Answer

Answer: Backfill all NULLs, add CHECK (col IS NOT NULL) NOT VALID, VALIDATE CONSTRAINT, then SET NOT NULL (the scan is skipped because a valid CHECK proves it), then drop the CHECK. See Adding NOT NULL safely.

8 — A CREATE INDEX CONCURRENTLY failed. What state is the database in and what do you do? Important ​

Answer

Answer: An INVALID index remains; the planner ignores it but writes still maintain it. Find it with pg_index.indisvalid = false, DROP INDEX CONCURRENTLY it (or REINDEX INDEX CONCURRENTLY), fix the cause (for example duplicates for a unique index) and retry. See Indexes online.

9 — Why is ALTER TYPE ... ADD VALUE awkward in a transactional migration, and what are the alternatives to an enum? Important ​

Answer

Answer: The new value cannot be used until the transaction commits, so use it in a later transaction or make the step non-transactional; enums cannot drop values. Alternatives are text plus a CHECK ... NOT VALID, or a lookup table with a foreign key. See Enum changes.

10 — What happens on a PostgreSQL hot standby when the primary runs an ALTER TABLE while a 10-minute report is running there? Important ​

Answer

Answer: The standby replays the ACCESS EXCLUSIVE lock, which conflicts with the report. Replay waits up to max_standby_streaming_delay (default 30 s) and then cancels the query; meanwhile replay_lag grows. See Migrations and replicas.

11 — Why is a failed multi-statement migration worse on MySQL than on PostgreSQL? Important ​

Answer

Answer: MySQL commits each DDL statement implicitly (each is atomic since 8.0, but the sequence is not), so earlier statements stay applied and the migration tool is left "dirty"; PostgreSQL rolls the whole transaction back. See Transactional DDL.

12 — Why is down() a poor rollback plan, and what is the alternative? Must-know ​

Answer

Answer: After the new column holds real data, down() destroys or cannot restore it. Because expand steps only add, the previous release still works on the expanded schema: redeploy it or flip a feature flag, and fix forward. See Release strategy.

Glossary ​

TermMeaning
ACCESS EXCLUSIVEPostgreSQL's strongest table lock; conflicts with every other mode, taken by most ALTER TABLE forms
Lock queueWaiting lock requests are granted in order; later requests wait behind an earlier waiting one
Soft block / hard blockA query waiting behind a queued ALTER versus a query blocked by a granted conflicting lock
lock_timeoutSetting that cancels a statement that waits too long for a lock (SQLSTATE 55P03)
statement_timeoutSetting that cancels a statement that runs too long (57014)
idle_in_transaction_session_timeoutSetting that terminates sessions idle inside a transaction
Metadata-only changeA catalog edit that does not touch row data
Table rewriteCopying every row into a new heap file; needs time and up to double the disk
relfilenodeThe file number of a table's storage; changes when the table is rewritten
Fast defaultPostgreSQL 11+ behaviour: a non-volatile default stored in the catalog (attmissingval) instead of rewriting
Volatile defaultA default function that can return different values per call, such as clock_timestamp() or gen_random_uuid()
Expand / migrate / contractParallel change: add the new form, move clients and data, then remove the old
Parallel changeSato's name for expand/contract
Dual writeWriting both the old and new representation during the migrate phase
BackfillFilling the new column or table from existing rows, in batches
Keyset batchA batch defined by primary-key range rather than OFFSET
NOT VALIDConstraint option: enforce for new writes, skip checking old rows
VALIDATE CONSTRAINTChecks existing rows of a NOT VALID constraint under SHARE UPDATE EXCLUSIVE
SHARE UPDATE EXCLUSIVETable lock that blocks other schema changes and VACUUM but not reads or writes
SHARE ROW EXCLUSIVELock taken by ADD FOREIGN KEY (both tables) and trigger changes
CREATE INDEX CONCURRENTLYIndex build in two scans that does not block writes; cannot run in a transaction
INVALID indexLeftover of a failed concurrent build; ignored by the planner, still maintained on writes
REINDEX CONCURRENTLYPostgreSQL 12+ online rebuild; leaves _ccnew/_ccold on failure
USING INDEXPromotes a prebuilt unique index to a UNIQUE or PRIMARY KEY constraint with a brief lock
Transactional DDLDDL that can be rolled back with the transaction (PostgreSQL, SQL Server, SQLite)
Implicit commitMySQL/Oracle behaviour: a DDL statement commits the open transaction
Atomic DDLMySQL 8.0+: one DDL statement is all-or-nothing, but sequences are not
ALGORITHM=INSTANTMySQL metadata-only alteration
ALGORITHM=INPLACEMySQL in-engine alteration, often with concurrent DML
ALGORITHM=COPYMySQL table-copy alteration that blocks writes
Metadata lock (MDL)MySQL's table-structure lock; queues like PostgreSQL's lock queue
gh-ostGitHub's triggerless online schema change tool for MySQL (ghost table + binlog)
pt-online-schema-changePercona's trigger-based online schema change tool for MySQL
Ghost tableThe new-schema copy that a tool fills and then swaps into place
Cut-overThe atomic rename that swaps the ghost table for the original
Replay lagHow far a standby's WAL replay is behind the primary (pg_stat_replication.replay_lag)
max_standby_streaming_delayHow long standby replay waits for conflicting queries before cancelling them
Forward-onlyStrategy of never running down() in production; fix by a new migration or flag flip
Feature flagRuntime switch controlling which code path or column is used
Blue/greenTwo environments with a router switch; both must work with the shared schema
$withinTransactionLaravel migration property; false runs the migration without a wrapping transaction
migrate --isolatedLaravel option that takes a cache lock so only one server runs migrations
migrate --pretendLaravel option that prints the SQL without running it
chunkByIdLaravel paging by primary key, safe when updating the rows being paged
golang-migrateGo migration library and CLI with up/down files and a dirty state
gooseGo migration tool with -- +goose Up/Down and NO TRANSACTION
AtlasSchema-as-code and versioned migration tool with migrate lint and --tx-mode
sqitchChange-plan migration tool with deploy/revert/verify scripts
Flyway / LiquibaseJVM migration tools: versioned SQL files and changesets
pgroll / ReshapePostgreSQL tools that serve old and new schema versions via views and triggers
squawkLinter for PostgreSQL migrations
strong_migrationsRails gem that blocks unsafe migrations and suggests safe recipes
pg_repack / pg_squeezeExtensions that rebuild bloated tables without long exclusive locks
SQLSTATE 55P03lock_not_available: the lock_timeout error

References ​

Built by Morteza Negahi