timescale/pg-aiguide/postgres-database-migration
Claude Code and agent skill by timescale/pg-aiguide
- community
Checking that the SKILL.md file is still in the repository.
Use this skill for planning, testing, and safely executing PostgreSQL schema migrations — especially when working with production data or shared databases. **Trigger when user asks to:** - Test a schema migration before applying it to production - Add, remove, or rename columns safely on a live table - Change a column's data type without downtime - Add or drop indexes, constraints, or foreign keys on large tables - Understand which ALTER TABLE operations lock the table - Roll back a failed migration - Plan a zero-downtime migration strategy - Fork a database to test a migration safely **Keywords:** migration, schema change, ALTER TABLE, add column, drop column, rename column, change type, zero downtime, lock, AccessExclusiveLock, concurrent index, forking, rollback, backfill, deploy Covers: lock-level reference for every common DDL operation, safe migration patterns, fork-based testing, zero-downtime column changes, index creation, constraint addition, backfill strategies, pre/post-migration validation, and rollback planning.
Install
npx vskill@latest install timescale/pg-aiguide/postgres-database-migrationSKILL.md
The same SKILL.md was published earlier as timescale/pg-aiguide/postgres-database-migration.
PostgreSQL Database Migrations
A schema migration that works on an empty dev database can fail, lock, or corrupt data on a production table with millions of rows. This guide covers how to assess risk, test against real data, and execute migrations safely.
DDL Lock Reference
Every schema change acquires a lock. The critical question is: does it block reads and writes, and for how long?
Fast, Non-Blocking Operations
These complete in milliseconds regardless of table size. They only hold a brief AccessExclusiveLock for the catalog update, not for data rewriting.
| Operation | Lock Level | Notes | |
|---|---|---|---|
ADD COLUMN (nullable, no default) | AccessExclusiveLock (brief) | Fast. No table rewrite. Metadata-only change. | |
ADD COLUMN ... DEFAULT x (PG 11+) | AccessExclusiveLock (brief) | Fast. Non-volatile defaults stored in catalog, not backfilled. | |
DROP COLUMN | AccessExclusiveLock (brief) | Fast. Column marked invisible; space reclaimed by VACUUM over time. | |
SET DEFAULT / DROP DEFAULT | AccessExclusiveLock (brief) | Metadata change only. Does not touch existing rows. | |
CREATE INDEX CONCURRENTLY | ShareUpdateExclusiveLock | Non-blocking. Allows reads and writes during build. Slower than regular index creation. | |
DROP INDEX CONCURRENTLY | ShareUpdateExclusiveLock | Non-blocking. Waits for queries using the index to finish, then drops. No table-level exclusive lock. | |
RENAME COLUMN | AccessExclusiveLock (brief) | Metadata change only. Fast. | |
RENAME TABLE | AccessExclusiveLock (brief) | Metadata change only. Fast. | |
ADD CONSTRAINT ... NOT VALID | ShareUpdateExclusiveLock | Adds constraint for new rows only. Does not scan existing data. | |
VALIDATE CONSTRAINT | ShareUpdateExclusiveLock | Scans existing rows but allows concurrent reads and writes. | |
CREATE/DROP TRIGGER | ShareRowExclusiveLock | Brief catalog update. |
Slow or Blocking Operations
These rewrite the table or scan all rows. On large tables, they can lock out all access for seconds to hours.
| Operation | Lock Level | Why It's Slow | |
|---|---|---|---|
ADD COLUMN ... DEFAULT x (volatile, e.g. now(), gen_random_uuid()) | AccessExclusiveLock | Full table rewrite. Every row gets the computed value. | |
ALTER COLUMN TYPE (most type changes) | AccessExclusiveLock | Full table rewrite to convert stored data. | |
SET NOT NULL (PG < 12, or without existing CHECK) | AccessExclusiveLock | Full table scan to verify no NULLs. See safe pattern below. | |
ADD CONSTRAINT ... CHECK/UNIQUE/FK (validated) | AccessExclusiveLock or ShareRowExclusiveLock | Scans all rows to verify, blocks writes. | |
CREATE INDEX (without CONCURRENTLY) | ShareLock | Blocks writes for the entire build duration. | |
CLUSTER | AccessExclusiveLock | Rewrites entire table in index order. | |
VACUUM FULL | AccessExclusiveLock | Rewrites table to reclaim space. |
Key insight: AccessExclusiveLock blocks everything — reads and writes. Even if the operation itself is fast (milliseconds), it must wait for all in-flight transactions to finish before acquiring the lock. A long-running query or idle transaction can cause an ALTER TABLE to hang and queue up all subsequent queries behind it.
Safe Migration Patterns
Add a Column
Drop a Column
Application coordination: Ensure your application no longer references the column before dropping it. For zero-downtime deploys, this requires two steps:
- Deploy code that doesn't read/write the column
- Then drop the column in a separate migration
Security caveat: DROP COLUMN does not physically delete the data. The column is marked as dropped in pg_attribute but the values remain on disk until VACUUM reclaims the space — and even then, a superuser could recover them. If the column contains sensitive data, run VACUUM FULL on the table after dropping, or use dump/restore to ensure the data is truly gone.
Rename a Column
Warning: This breaks any application code, views, or functions that reference the old column name. For zero-downtime deploys, use the column-swap pattern instead:
- Add the new column
- Deploy code that writes to both columns
- Backfill old rows
- Deploy code that reads from the new column
- Drop the old column
Change a Column Type
Most type changes rewrite the entire table. Safe alternatives:
Exception: Some casts don't require a rewrite and are fast:
| From | To | Rewrite? | |
|---|---|---|---|
VARCHAR(n) → VARCHAR(m) where m > n | No | Metadata only | |
VARCHAR(n) → TEXT | No | Metadata only | |
NUMERIC(p,s) → NUMERIC(p2,s) where p2 > p (same scale) | No | Metadata only | |
INTEGER → BIGINT | Yes | Full rewrite | |
TIMESTAMP → TIMESTAMPTZ | Yes | Full rewrite |
Add a NOT NULL Constraint
Add a Foreign Key
Add an Index
Add a Unique Constraint
Redefine a Primary Key
Redefining a PK (e.g., switching from id to a composite key, or from int to bigint) requires both a UNIQUE constraint and NOT NULL — both of which can cause long-lasting locks if done naively. The zero-downtime approach builds each ingredient separately:
Why this works: Step 5 is fast because Postgres reuses the already-built unique index and recognizes the existing CHECK constraint, skipping both the index build and the full-table NOT NULL scan (PG12+).
Drop a Constraint
Backfill Strategies
Always backfill in batches — never in a single UPDATE. See backfill-strategies for batch-by-PK patterns, resumable progress tracking, and tuning guidance.
Migration Validation
Run validation queries before and after every migration. See validation-queries for the full set of checks: NULL detection, duplicate detection, orphan rows, cast failures, duration estimation, schema verification, data integrity, and query performance.
Rollback Planning
Every migration should have a rollback plan documented before execution.
Reversible Operations
| Operation | Rollback | |
|---|---|---|
ADD COLUMN | DROP COLUMN | |
ADD CONSTRAINT | DROP CONSTRAINT | |
CREATE INDEX | DROP INDEX | |
RENAME COLUMN x TO y | RENAME COLUMN y TO x | |
SET DEFAULT x | SET DEFAULT old_value or DROP DEFAULT | |
ADD COLUMN new + DROP COLUMN old | Cannot directly undo — need to re-add old column and backfill from a backup |
Irreversible Operations
These require restoring from a backup or the database fork to undo:
- `DROP COLUMN` — data is gone once VACUUM reclaims it
- `ALTER COLUMN TYPE` with lossy cast (e.g.,
NUMERIC→INTEGER,TEXT→VARCHAR(50)) - `DELETE` / `TRUNCATE` during data cleanup
- `DROP TABLE`
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 95 of 100Pattern checks on the skill's files.
- Model reviewPassed
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/postgres-database-migration/SKILL.md
Popularity
- Repository stars
- 1,847
- Repository forks
- 110
- 7-day trend score
- 38
Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/timescale/pg-aiguide/postgres-database-migration)