Database Migrations with Claude Code

Claude can write migrations, but database changes need more care than most code. Here's the process that keeps data safe.

Database migrations are the highest-stakes code in most applications. A bug in a migration can corrupt data, lock tables, or be irreversible. Claude Code can write them, but the review process needs to be more rigorous than for application code.

Always specify reversibility

Every migration should have an up and a down. Ask Claude to include both and to think explicitly about whether the down is actually possible. Some migrations are genuinely irreversible (dropping a column with data, changing a column type that truncates values) and those need to be flagged clearly, not silently skipped.

Add to every migration prompt: "Include a down migration. If the migration is irreversible, note it explicitly in a comment and explain why."

Test on a copy of production data

The staging environment with synthetic data won't catch problems that production data will. Before running any significant migration on production: dump production, restore to a test environment, run the migration there, verify the data looks correct.

Claude can help write the verification queries: "After this migration runs, write a query to verify the data was transformed correctly."

What Claude gets wrong on migrations

Lock behavior. Some ALTER TABLE operations lock the entire table in Postgres. Claude doesn't always flag this. For large tables, locking operations need to be replaced with zero-downtime alternatives (adding a column as nullable first, backfilling, then adding the constraint).

Index creation. Creating an index without CONCURRENTLY will lock the table. Claude sometimes forgets this on large tables. Add "this table has millions of rows" to your prompt and Claude will correctly use CONCURRENTLY.

NOT NULL additions. Adding a NOT NULL column without a default to an existing table will fail if there are any rows. Claude sometimes generates this pattern incorrectly.

The review checklist for migrations

Run through this on every migration Claude produces before it gets near production.