PostgreSQL 11–17 DDL Safety 100% Browser-Local · Zero SQL Upload

PostgreSQL Migration Lock & Downtime Risk Checker

What is a PostgreSQL migration lock checker? A PostgreSQL migration lock checker is a static DDL analyzer that inspects SQL schema changes before deployment to report exact table lock modes, full-heap rewrites, transaction-block violations, and version-specific hazards across PostgreSQL 11–17. It prevents lock-queue amplification: when an ALTER TABLE statement requests an ACCESS EXCLUSIVE lock while a slow SELECT holds ACCESS SHARE, the DDL statement enters PostgreSQL's FIFO wait queue rather than running immediately. Because PostgreSQL blocks incoming lock requests that conflict with waiting heavyweight locks, every subsequent SELECT (ACCESS SHARE) and INSERT, UPDATE, or DELETE (ROW EXCLUSIVE) piles up behind the queued DDL statement, saturating application connection pools within seconds.

Load Sample:

Migration SQL Input

Parsed locally via JS tokenizer
Supports multi-action ALTER TABLE, comments, and $$ dollar quotes. 0 lines

Lock & Rewrite Audit

Blast radius: —
BLOCK MERGE
ACCESS EXCLUSIVE
Risk Score0 / 100
Critical0
Warnings0
Safe Ops0

Auto-Rewritten Safe Zero-Downtime Migration Script

-- Analyze a migration above to generate the safe rewrite.

Browser Paste Checkers vs. Production CI PR Gatekeeper Kit ($39)

Ad-hoc browser sandboxes (like manual SQL paste tools, PGlite WASM playgrounds, or locksmith CLI wrappers) are great for quick spot checks—until a 6-file Prisma or Drizzle PR merges Friday afternoon without a lock_timeout retry loop.

Capability Browser Paste Checkers (e.g. PGlite / locksmith / Single-File Linters) Production CI PR Gatekeeper Kit ($39 One-Time GitHub Action Pack)
Enforcement Trigger Manual copy-paste when an engineer remembers to check before deploy Automatic blocking check on every Pull Request touching migrations/**
Multi-Migration State Single snippet only; misses table/index state created in earlier PR files Tracks cross-file schema lineage across ordered Prisma, Drizzle, Alembic & Knex diffs
Lock Queue Guardrails Static SQL suggestion only; deploy runner still hangs if lock waits Includes pg-safe-migrate Safe-Retry Wrapper (lock_timeout=2s + jittered backoff)
PR Review UX Manual screenshot or Slack paste Inline GitHub PR sticky comment + SARIF line annotations + exact Expand-Contract patch
Cost & Data Privacy $0 browser tool (100% local on this page) $39 one-time repo buyout (runs 100% inside your own GitHub Actions runner, $0/seat/mo)

Automate This Lock Check in GitHub PRs — $39 One-Time Team Pack

The browser analyzer above is 100% free with no account required. For engineering teams who want automatic merge blocking before production deploys, our self-hosted CI pack runs completely offline in your own runner:

  • Zero-dependency Node CLI returning deterministic exit 1 on ACCESS EXCLUSIVE or table rewrites
  • GitHub Actions PR comment bot posting line-by-line lock risk tables & safe SQL patches
  • Supports Prisma, Drizzle, Flyway, and Alembic migration directories + .pglockrc.json allowlists
Request $39 Team Pack License No recurring SaaS subscription · No DB credentials leave your CI · See CodexTheme pricing policy

PostgreSQL 11–17 DDL Lock & Rewrite Reference Matrix

DDL Operation Lock Acquired Blocks Reads Blocks Writes Table Rewrite PG Version Note Zero-Downtime Pattern
CREATE INDEXSHARENoYesNoPG 11-17: Holds SHARE across the full heap scan and sort, blocking INSERT, UPDATE, DELETE, and MERGE (PG 15+). PG 11+ parallel B-tree builds (max_parallel_maintenance_workers) and PG 13+ B-tree deduplication shorten build duration but still stall all writes.CREATE INDEX CONCURRENTLY idx_orders_acct ON orders (account_id); -- execute outside any transaction block
CREATE INDEX CONCURRENTLYSHARE UPDATE EXCLUSIVENoNoNoPG 11-17: Builds the index across two heap scans and three internal transactions without blocking SELECT or DML, waiting only for older snapshots to commit. PG 14+ stops concurrent index builds from pinning global xmin horizons on unrelated tables. Fails inside BEGIN/COMMIT (SQLSTATE 25001) and leaves an indisvalid = false index on failure.CREATE INDEX CONCURRENTLY idx_orders_acct ON orders (account_id); -- verify pg_index.indisvalid = true afterward
DROP INDEX (vs DROP INDEX CONCURRENTLY)ACCESS EXCLUSIVE (SHARE UPDATE EXCLUSIVE with CONCURRENTLY)YesYesNoPG 11-17: Plain DROP INDEX acquires ACCESS EXCLUSIVE on the parent table, queueing behind active SELECT queries. DROP INDEX CONCURRENTLY downgrades the lock to SHARE UPDATE EXCLUSIVE (blocking neither reads nor writes) but forbids transaction blocks, CASCADE, and multi-index lists.DROP INDEX CONCURRENTLY IF EXISTS idx_orders_acct; -- run in autocommit mode, one index per statement
ALTER COLUMN TYPEACCESS EXCLUSIVEYesYesConditionalPG 11-17: Always acquires ACCESS EXCLUSIVE. Binary-coercible widenings—VARCHAR(n) to VARCHAR(m) (m > n), VARCHAR(n) to TEXT, NUMERIC(p,s) to NUMERIC(p2,s) (p2 > p, identical scale s) or unconstrained NUMERIC, and PG 12+ TIMESTAMP <-> TIMESTAMPTZ when session TimeZone = 'UTC'—skip heap rewrites unless expression/partial indexes depend on the column. INT -> BIGINT or scale reductions rewrite the entire heap and all indexes.Safe widen (VARCHAR -> TEXT): guard with SET lock_timeout = '2s'. Incompatible change (INT -> BIGINT): Expand-Contract with new column, trigger dual-write, batched backfill, and cutover.
ADD COLUMN ... DEFAULT <constant>ACCESS EXCLUSIVEYesYesNoPG 11-17: Non-volatile defaults (constants like 0, false, 'pending', or IMMUTABLE/STABLE expressions) evaluate once at DDL time and store the binary datum in pg_attribute.attmissingval (atthasmissing = true), skipping the heap rewrite even with NOT NULL. (PG 10 and earlier rewrote the entire table.) Still acquires brief ACCESS EXCLUSIVE.SET LOCAL lock_timeout = '2s'; ALTER TABLE orders ADD COLUMN state TEXT NOT NULL DEFAULT 'pending';
ADD COLUMN ... DEFAULT <volatile>ACCESS EXCLUSIVEYesYesYesPG 11-17: VOLATILE defaults—gen_random_uuid(), random(), clock_timestamp(), nextval()—bypass attmissingval and rewrite every heap page and index under ACCESS EXCLUSIVE. Subtlety: now() / CURRENT_TIMESTAMP is STABLE in PG 11+, avoiding a rewrite by freezing one DDL-time timestamp onto all legacy rows, whereas clock_timestamp() forces a full rewrite.ALTER TABLE orders ADD COLUMN ext_id UUID; ALTER TABLE orders ALTER COLUMN ext_id SET DEFAULT gen_random_uuid(); -- backfill NULL rows in PK batches
ALTER COLUMN ... SET NOT NULLACCESS EXCLUSIVEYesYesNoPG 11: Always performs a full sequential heap scan under ACCESS EXCLUSIVE. PG 12-17: Skips the table scan if a validated CHECK constraint (convalidated = true, e.g. CHECK (col IS NOT NULL)) already proves no NULLs exist. Native NOT NULL NOT VALID syntax was reverted prior to PG 17 GA, keeping the CHECK pattern mandatory through PG 17.ALTER TABLE tbl ADD CONSTRAINT tbl_col_nn CHECK (col IS NOT NULL) NOT VALID; ALTER TABLE tbl VALIDATE CONSTRAINT tbl_col_nn; ALTER TABLE tbl ALTER COLUMN col SET NOT NULL; ALTER TABLE tbl DROP CONSTRAINT tbl_col_nn;
ADD CONSTRAINT ... FOREIGN KEYSHARE ROW EXCLUSIVENoYesNoPG 11-17: Direct ADD FOREIGN KEY acquires SHARE ROW EXCLUSIVE on both the child table and referenced parent table, blocking INSERT, UPDATE, and DELETE on both tables during the validation scan. Appending NOT VALID holds SHARE ROW EXCLUSIVE only for millisecond trigger catalog updates; VALIDATE CONSTRAINT uses SHARE UPDATE EXCLUSIVE on child and ROW SHARE on parent.ALTER TABLE orders ADD CONSTRAINT fk_orders_user FOREIGN KEY (user_id) REFERENCES users (id) NOT VALID; ALTER TABLE orders VALIDATE CONSTRAINT fk_orders_user;
ADD CONSTRAINT ... CHECKACCESS EXCLUSIVEYesYesNoPG 11-17: Direct ADD CONSTRAINT ... CHECK holds ACCESS EXCLUSIVE across a full sequential scan. Adding NOT VALID reduces ACCESS EXCLUSIVE to an instant catalog write that enforces the rule on new/updated tuples immediately; VALIDATE CONSTRAINT then scans historical rows under SHARE UPDATE EXCLUSIVE without blocking reads or writes.SET LOCAL lock_timeout = '2s'; ALTER TABLE orders ADD CONSTRAINT chk_total CHECK (total_cents >= 0) NOT VALID; -- then run ALTER TABLE orders VALIDATE CONSTRAINT chk_total; in a new transaction
ADD CONSTRAINT ... UNIQUE / PRIMARY KEYACCESS EXCLUSIVEYesYesNoPG 11-17: Inline ADD UNIQUE or ADD PRIMARY KEY holds ACCESS EXCLUSIVE for the entire B-tree index build (plus a sequential NULL scan for PRIMARY KEY unless columns are already NOT NULL). Building a UNIQUE index concurrently first and attaching it via USING INDEX reduces ACCESS EXCLUSIVE to a brief metadata update.CREATE UNIQUE INDEX CONCURRENTLY idx_users_email_uniq ON users (email); ALTER TABLE users ADD CONSTRAINT users_email_key UNIQUE USING INDEX idx_users_email_uniq;
DROP COLUMN / RENAME COLUMNACCESS EXCLUSIVEYesYesNoPG 11-17: DROP COLUMN sets pg_attribute.attisdropped = true without rewriting tuples or freeing disk blocks immediately; RENAME COLUMN updates pg_attribute.attname in place. Both take brief ACCESS EXCLUSIVE (vulnerable to lock-queue amplification) and break live app queries or ORM models still referencing the column.Deploy application code removing column references first (for RENAME: add new column, dual-write, backfill, switch reads), then run DROP COLUMN under SET LOCAL lock_timeout = '2s'.
ATTACH PARTITIONACCESS EXCLUSIVE (child & PG 11 parent) / SHARE UPDATE EXCLUSIVE (PG 12+ parent)YesYesNoPG 11: Acquires ACCESS EXCLUSIVE on both partitioned parent and attached table. PG 12-17: Lowers the parent table lock to SHARE UPDATE EXCLUSIVE, but still acquires ACCESS EXCLUSIVE on the child table (and scans both the child and any DEFAULT partition) unless pre-validated CHECK constraints already prove partition bounds.Add CHECK (bounds) NOT VALID on child (and inverse CHECK on any DEFAULT partition), VALIDATE CONSTRAINT under SHARE UPDATE EXCLUSIVE, then run ALTER TABLE parent ATTACH PARTITION child FOR VALUES ...; under lock_timeout.

5-Step Zero-Downtime PostgreSQL Migration Checklist

  1. 1

    Guard every DDL statement with lock_timeout, statement_timeout, and transaction-external retries

    PostgreSQL defaults lock_timeout to 0 (infinite wait), allowing a fast ALTER TABLE to sit behind an analytical SELECT and block every incoming query. Set a 1s–3s lock_timeout and bounded statement_timeout for catalog DDL, and run backoff sleeps outside the failed transaction so aborted attempts never hold backend_xmin or partial locks.

    -- Run per short catalog DDL attempt from your migration runner (retry on SQLSTATE 55P03):
    BEGIN;
    SET LOCAL lock_timeout = '2s';
    SET LOCAL statement_timeout = '10s';
    ALTER TABLE orders ADD COLUMN fulfilled_by TEXT NOT NULL DEFAULT 'system';
    COMMIT;
  2. 2

    Execute CREATE INDEX CONCURRENTLY and DROP INDEX CONCURRENTLY outside transaction blocks

    Concurrent index builds and drops acquire SHARE UPDATE EXCLUSIVE so reads and writes continue uninterrupted, but PostgreSQL aborts with SQLSTATE 25001 inside BEGIN/COMMIT or multi-statement simple-query batches. Run one statement per autocommit execution, raise statement_timeout for the scan, and check pg_index.indisvalid afterward to drop any failed INVALID index.

    -- Autocommit session (no BEGIN/COMMIT; one statement per wire call where required):
    SET statement_timeout = '60min';
    DROP INDEX CONCURRENTLY IF EXISTS idx_orders_customer_created;
    CREATE INDEX CONCURRENTLY idx_orders_customer_created ON orders (customer_id, created_at DESC);
    
    -- Verify no broken index remains:
    SELECT indexrelid::regclass AS index_name, indisvalid
    FROM pg_index
    WHERE indexrelid = 'idx_orders_customer_created'::regclass;
  3. 3

    Split CHECK and FOREIGN KEY constraints into NOT VALID creation and VALIDATE CONSTRAINT

    Add the constraint with NOT VALID inside a lock_timeout-guarded transaction so PostgreSQL updates the catalogs and begins enforcing rules on new writes in milliseconds without scanning historical tuples. Commit immediately to release the heavy lock, then run VALIDATE CONSTRAINT in a second transaction under SHARE UPDATE EXCLUSIVE.

    -- Transaction 1: millisecond catalog lock on child and parent
    BEGIN;
    SET LOCAL lock_timeout = '2s';
    ALTER TABLE order_items
      ADD CONSTRAINT fk_order_items_order
      FOREIGN KEY (order_id) REFERENCES orders (id) NOT VALID;
    COMMIT;
    
    -- Transaction 2: non-blocking historical scan (SHARE UPDATE EXCLUSIVE)
    SET statement_timeout = '30min';
    ALTER TABLE order_items VALIDATE CONSTRAINT fk_order_items_order;
  4. 4

    Enforce NOT NULL on PostgreSQL 12+ via a pre-validated CHECK (col IS NOT NULL) constraint

    Direct ALTER COLUMN ... SET NOT NULL holds ACCESS EXCLUSIVE for a full heap scan unless PostgreSQL 12–17 finds an already-validated CHECK constraint proving no NULL values exist. Add CHECK (col IS NOT NULL) NOT VALID, validate it online, execute SET NOT NULL for an instant catalog flip, and drop the temporary CHECK constraint.

    -- Step 1: fast metadata write
    BEGIN;
    SET LOCAL lock_timeout = '2s';
    ALTER TABLE users ADD CONSTRAINT users_org_id_nn CHECK (org_id IS NOT NULL) NOT VALID;
    COMMIT;
    
    -- Step 2: online scan under SHARE UPDATE EXCLUSIVE
    ALTER TABLE users VALIDATE CONSTRAINT users_org_id_nn;
    
    -- Step 3: instant SET NOT NULL on PG 12-17 + cleanup
    BEGIN;
    SET LOCAL lock_timeout = '2s';
    ALTER TABLE users ALTER COLUMN org_id SET NOT NULL;
    ALTER TABLE users DROP CONSTRAINT users_org_id_nn;
    COMMIT;
  5. 5

    Apply Expand-Contract for column renames, drops, and incompatible type rewrites

    Avoid RENAME COLUMN and rewrite-inducing ALTER COLUMN TYPE (such as INTEGER to BIGINT) on live tables. Add the new column, mirror writes with a BEFORE INSERT OR UPDATE trigger or dual-write code, backfill historical rows in small primary-key batches with commits between chunks so autovacuum reclaims dead tuples, cut application reads over, and drop the legacy column last.

    -- Phase 1 (Expand): add target column + dual-write trigger
    BEGIN;
    SET LOCAL lock_timeout = '2s';
    ALTER TABLE events ADD COLUMN id_v2 BIGINT;
    CREATE OR REPLACE FUNCTION sync_events_id_v2() RETURNS trigger LANGUAGE plpgsql AS $$
    BEGIN
      NEW.id_v2 := NEW.id;
      RETURN NEW;
    END $$;
    CREATE TRIGGER trg_sync_events_id_v2 BEFORE INSERT OR UPDATE ON events
      FOR EACH ROW EXECUTE FUNCTION sync_events_id_v2();
    COMMIT;
    
    -- Phase 2 (Backfill one bounded PK batch per transaction):
    UPDATE events SET id_v2 = id WHERE id > 0 AND id <= 50000 AND id_v2 IS NULL;

Why a 5ms ACCESS EXCLUSIVE Lock Causes a 5-Minute Outage

Most PostgreSQL migration outages are triggered not by multi-hour table rewrites, but by metadata-only ALTER TABLE commands that finish in under five milliseconds on an idle staging server. Operations such as ADD COLUMN, DROP COLUMN, RENAME COLUMN, and ADD CONSTRAINT ... CHECK ... NOT VALID acquire ACCESS EXCLUSIVE—PostgreSQL's strictest heavyweight table lock, which conflicts with every lock mode in pg_locks, including the ACCESS SHARE lock acquired by plain SELECT queries, autovacuum workers, and foreign-key lookup checks.

Outages occur through FIFO lock-queue amplification inside ProcSleep. Suppose an analytics query, pg_dump worker, or leaked idle in transaction session holds ACCESS SHARE on orders for 90 seconds. Five seconds in, your runner executes ALTER TABLE orders ADD COLUMN retry_count INT DEFAULT 0 with default lock_timeout = 0. Blocked by ACCESS SHARE, the ALTER TABLE enters the wait queue (granted = false). To prevent writer starvation, PostgreSQL blocks incoming lock requests that conflict with queued waiters, forcing every new SELECT (ACCESS SHARE) and INSERT, UPDATE, or DELETE (ROW EXCLUSIVE) behind the waiting DDL.

At 500 queries per second, a 100-connection PgBouncer or HikariCP pool exhausts in 200 milliseconds. Read-only API endpoints start returning 502 and 504 errors across unrelated application routes that merely join or read from the table, turning a five-millisecond catalog edit into an 85-second outage. Enforcing SET LOCAL lock_timeout = '2s' aborts the DDL attempt with SQLSTATE 55P03 before the queue deepens, immediately releasing queued readers so your migration runner can sleep outside the transaction and retry cleanly.

SELECT blocked.pid, blocked.wait_event,
       now() - blocked.query_start AS wait_time,
       pg_blocking_pids(blocked.pid) AS blockers,
       LEFT(blocked.query, 70) AS query
FROM pg_stat_activity AS blocked
WHERE CARDINALITY(pg_blocking_pids(blocked.pid)) > 0;
Field Note: Never run production DDL with lock_timeout = 0. Combine SET LOCAL lock_timeout = '2s' with idle_in_transaction_session_timeout on app roles.

Fast ADD COLUMN ... DEFAULT in PG 11+ vs Volatile Traps

Before PostgreSQL 11, ALTER TABLE ... ADD COLUMN ... DEFAULT <expr> rewrote every heap page and rebuilt every index on the relation while holding ACCESS EXCLUSIVE. Since PostgreSQL 11, ATExecAddColumn in tablecmds.c inspects the default expression tree using contain_volatile_functions(). When that check returns false—covering literal constants as well as IMMUTABLE and STABLE SQL or C functions—PostgreSQL evaluates the expression once at DDL execution time, stores the serialized binary datum inside pg_attribute.attmissingval, and flips atthasmissing = true. Pre-existing heap tuples remain untouched on disk with their shorter attribute array; sequential and index scans substitute attmissingval in memory during slot tuple deforming, even when NOT NULL is declared alongside DEFAULT.

That optimization vanishes when the default contains any VOLATILE function (provolatile = 'v'), including gen_random_uuid(), uuid_generate_v4(), random(), clock_timestamp(), and nextval() (used by SERIAL, BIGSERIAL, and GENERATED ... AS IDENTITY columns added to populated tables). Because each existing row needs an independently generated datum, PostgreSQL disables attmissingval and invokes ATRewriteTables, holding ACCESS EXCLUSIVE across a full heap and index rebuild on a 200 GB table while doubling peak disk consumption before commit and saturating streaming replication slots with WAL.

Timestamp defaults hide a sharp distinction between now() and clock_timestamp(). In pg_proc, now() and CURRENT_TIMESTAMP alias transaction_timestamp(), marked STABLE (provolatile = 's'). On PG 11–17, ADD COLUMN created_at TIMESTAMPTZ DEFAULT now() avoids a rewrite—but stamps every historical row with the single migration timestamp, skewing historical records, whereas switching to clock_timestamp() (VOLATILE) triggers a full table rewrite. For dynamic defaults, add a nullable column with no default, attach SET DEFAULT for future inserts, and backfill NULLs in batches.

BEGIN;
SET LOCAL lock_timeout = '2s';
ALTER TABLE invoices ADD COLUMN public_id UUID;
ALTER TABLE invoices ALTER COLUMN public_id SET DEFAULT gen_random_uuid();
COMMIT;

UPDATE invoices SET public_id = gen_random_uuid()
WHERE id >= 1 AND id < 50001 AND public_id IS NULL;
Field Note: pg_proc.provolatile = 'i' or 's' (including now()) uses attmissingval without rewriting; 'v' (gen_random_uuid(), clock_timestamp(), nextval()) rewrites the entire table.

Zero-Downtime SET NOT NULL & FOREIGN KEY via NOT VALID

Adding a constraint combines catalog registration for new writes with a scan verifying historical rows, and lock severity depends on the constraint type. Direct ADD CONSTRAINT ... CHECK and PG 11 SET NOT NULL hold ACCESS EXCLUSIVE across a full sequential scan, blocking reads and writes. Direct ADD CONSTRAINT ... FOREIGN KEY acquires SHARE ROW EXCLUSIVE on both the child table and referenced parent table: SELECTs (ACCESS SHARE) continue, but INSERT, UPDATE, and DELETE (ROW EXCLUSIVE) stall on both tables—so adding a foreign key on audit_logs freezes writes on users.

Appending NOT VALID splits those phases. ALTER TABLE child ADD CONSTRAINT ... FOREIGN KEY ... NOT VALID still takes SHARE ROW EXCLUSIVE on both tables, and CHECK ... NOT VALID takes ACCESS EXCLUSIVE, but PostgreSQL sets pg_constraint.convalidated = false and skips the scan. Once committed in milliseconds, new writes enforce the constraint immediately. Running ALTER TABLE ... VALIDATE CONSTRAINT in a second transaction takes only SHARE UPDATE EXCLUSIVE on the child table (and ROW SHARE on the parent for foreign keys), blocking neither reads nor writes.

PostgreSQL 12–17 applies this exact mechanism to SET NOT NULL. Because native NOT NULL ... NOT VALID catalog syntax was reverted prior to the PostgreSQL 17 GA release, ALTER COLUMN ... SET NOT NULL still acquires ACCESS EXCLUSIVE through PG 17 and offers no inline NOT VALID keyword. However, starting in PostgreSQL 12, SET NOT NULL inspects pg_constraint for an existing convalidated = true CHECK (col IS NOT NULL) clause; finding one, PostgreSQL skips the sequential heap scan entirely, flips pg_attribute.attnotnull = true in milliseconds under SET LOCAL lock_timeout = '2s', and lets you drop the helper CHECK constraint immediately.

CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_inv_acct ON invoices (account_id);
BEGIN;
SET LOCAL lock_timeout = '2s';
ALTER TABLE invoices ADD CONSTRAINT inv_acct_fk
  FOREIGN KEY (account_id) REFERENCES accounts (id) NOT VALID;
COMMIT;
ALTER TABLE invoices VALIDATE CONSTRAINT inv_acct_fk;
Field Note: Never run ADD CONSTRAINT ... NOT VALID and VALIDATE CONSTRAINT inside one BEGIN ... COMMIT block, or the initial heavy lock persists through the full scan.

ORM Transaction Wrappers Breaking CONCURRENTLY

CREATE INDEX CONCURRENTLY, DROP INDEX CONCURRENTLY, and REINDEX CONCURRENTLY (PG 12+) fail inside transaction blocks because PostgreSQL commits catalog changes across three internal transactions while waiting on virtual transaction IDs (virtualxid) between two heap scans. Any open BEGIN—or multiple semicolon-separated statements sent in one PostgreSQL simple-query protocol call (PQexec), which creates an implicit transaction block—aborts immediately with SQLSTATE 25001 (cannot run inside a transaction block).

Prisma Migrate and Alembic require explicit isolation. Prisma sends migration.sql over raw simple-query execution and offers no transaction toggle: create the migration with npx prisma migrate dev --create-only and keep strictly one CREATE INDEX CONCURRENTLY statement in the file, as adding a second index or SET command creates an implicit multi-statement transaction. In Alembic, wrap op.create_index(..., postgresql_concurrently=True) inside with op.get_context().autocommit_block():, which commits the active migration transaction before switching the connection to AUTOCOMMIT.

In Flyway, place CONCURRENTLY in a standalone V*__*.sql file containing zero transactional DDL statements, and explicitly set executeInTransaction=false in a companion V4__idx.sql.conf sidecar file (Community/Teams) or a -- flyway:executeInTransaction=false header comment (Teams/Enterprise) so mixed-statement heuristics cannot re-enable BEGIN. Drizzle ORM's drizzle-kit migrate executes migration files inside a single session.transaction() wrapper, and --> statement-breakpoint only splits SQL strings within that same open transaction—so generate a stub with drizzle-kit generate --custom and run CONCURRENTLY from a standalone non-transactional client script. Always precede retries with an autocommit DROP INDEX CONCURRENTLY IF EXISTS step to clear indisvalid = false leftovers that otherwise penalize every write.

# Alembic autocommit_block():
with op.get_context().autocommit_block():
    op.create_index("idx_ev_org", "events", ["org_id"], postgresql_concurrently=True)

-- Flyway: V4__idx.sql.conf -> executeInTransaction=false
-- Prisma migration.sql (sole statement in file):
CREATE INDEX CONCURRENTLY "idx_ev_org" ON "events"("org_id");
Field Note: Sending 'SET statement_timeout = 0; CREATE INDEX CONCURRENTLY ...;' in one PQexec string creates an implicit transaction block and fails with SQLSTATE 25001.

PostgreSQL Migration Lock Checker FAQ

Why does a fast metadata-only ALTER TABLE still cause downtime in PostgreSQL?

Metadata-only commands like ADD COLUMN, DROP COLUMN, or ADD CONSTRAINT ... CHECK ... NOT VALID still request an ACCESS EXCLUSIVE lock. If a slow SELECT query or an idle in transaction session already holds ACCESS SHARE on that table, the ALTER TABLE waits in PostgreSQL's FIFO lock queue, and every new SELECT, INSERT, UPDATE, and DELETE queues behind the waiting DDL. With default lock_timeout = 0, application connection pools exhaust within seconds; setting SET LOCAL lock_timeout = '2s' aborts the wait fast so you can retry cleanly.

Does ALTER TABLE ... ADD COLUMN ... DEFAULT now() rewrite the table in PostgreSQL 11–17?

No—in PostgreSQL 11–17, now() and CURRENT_TIMESTAMP resolve to transaction_timestamp(), which is marked STABLE (provolatile = 's'), so PostgreSQL evaluates it once during the DDL statement and stores that single timestamp in pg_attribute.attmissingval without rewriting the heap (whereas PG 10 rewrote the table). However, every existing row receives the migration's execution timestamp rather than NULL, while VOLATILE functions such as clock_timestamp(), gen_random_uuid(), random(), and nextval() bypass attmissingval and force a full table and index rewrite under ACCESS EXCLUSIVE.

How do I enforce SET NOT NULL without blocking reads and writes on PostgreSQL 12–17?

Run a four-step sequence across separate transactions: (1) ALTER TABLE tbl ADD CONSTRAINT tbl_col_nn CHECK (col IS NOT NULL) NOT VALID under SET LOCAL lock_timeout = '2s'; (2) ALTER TABLE tbl VALIDATE CONSTRAINT tbl_col_nn, which scans existing rows under SHARE UPDATE EXCLUSIVE without blocking reads or writes; (3) ALTER TABLE tbl ALTER COLUMN col SET NOT NULL under lock_timeout, which on PG 12–17 detects the validated CHECK constraint and skips the sequential scan (PG 11 still scans; native NOT NULL NOT VALID was reverted before PG 17 GA); and (4) DROP CONSTRAINT tbl_col_nn.

What happens if CREATE INDEX CONCURRENTLY fails partway through, and how do I clean it up?

PostgreSQL leaves behind an index entry with pg_index.indisvalid = false. The query planner ignores an INVALID index for SELECT queries, but INSERT, UPDATE, and HOT-chain checks still pay write-maintenance overhead on that broken index. On PostgreSQL 12–17 you can rebuild it online with REINDEX INDEX CONCURRENTLY idx_name (unless duplicate rows broke a UNIQUE build), or run DROP INDEX CONCURRENTLY idx_name outside a transaction block, fix any duplicate keys or statement_timeout limits, and re-run CREATE INDEX CONCURRENTLY.

Why does adding a FOREIGN KEY constraint block writes on the referenced parent table?

PostgreSQL enforces foreign keys with internal RI_ConstraintTrigger triggers on both tables, so ALTER TABLE child ADD CONSTRAINT ... FOREIGN KEY acquires SHARE ROW EXCLUSIVE on both the child table and the referenced parent table. Without NOT VALID, PostgreSQL holds SHARE ROW EXCLUSIVE across the full validation join, blocking INSERT, UPDATE, DELETE, and MERGE (ROW EXCLUSIVE) on high-traffic parent tables like users or accounts. Adding the constraint with NOT VALID releases SHARE ROW EXCLUSIVE in milliseconds, and VALIDATE CONSTRAINT takes only SHARE UPDATE EXCLUSIVE on the child and ROW SHARE on the parent.

Which ALTER COLUMN TYPE changes skip a full table rewrite in PostgreSQL 11–17?

PostgreSQL skips the heap rewrite for binary-coercible widenings: VARCHAR(n) to VARCHAR(m) where m > n, VARCHAR(n) to TEXT, NUMERIC(p,s) to NUMERIC(p2,s) where p2 > p with identical scale s or unconstrained NUMERIC, VARBIT(n) to wider VARBIT(m), and on PostgreSQL 12+ conversions between TIMESTAMP and TIMESTAMPTZ when the session TimeZone is 'UTC'. Widening INT4 to BIGINT (INT8), shrinking VARCHAR length, changing NUMERIC scale, or altering columns referenced by partial or expression indexes triggers table or index rebuilds under ACCESS EXCLUSIVE.

How do I attach a partition in PostgreSQL 12–17 without holding ACCESS EXCLUSIVE across a full scan?

Starting in PostgreSQL 12, ALTER TABLE parent ATTACH PARTITION lowers the lock on the partitioned parent table from ACCESS EXCLUSIVE (PG 11) to SHARE UPDATE EXCLUSIVE, though the child table being attached still takes ACCESS EXCLUSIVE. To skip the sequential validation scan during attachment, first add a matching CHECK constraint with NOT VALID on the child table—and a negating CHECK constraint on any DEFAULT partition—then run VALIDATE CONSTRAINT under SHARE UPDATE EXCLUSIVE before executing ATTACH PARTITION under a short lock_timeout.

More Developer Tools & Guides on CodexTheme