“Add this column and deploy it” leaves too much unsaid. A useful database migration prompt should make the coding agent inspect the repository, identify data and compatibility risks, rehearse the change outside production, and define how the result will be verified.

The ten prompts below cover that process for repository-aware tools such as Claude Code, Codex, Cursor, and Copilot. Adapt every command to your database, framework, hosting platform, and backup process. If you need prompts for schema design and query work as well, start with the database prompt library. For the broader development process, read the vibe coding workflow from brief to verified pull request.

A migration command that exits successfully proves only that the command completed. Verify the data, application behavior, deployment state, and recovery options separately.

Why database migrations need extra review

A code deployment can often be reverted to a previous artifact. That does not undo database mutations, queued work, configuration changes, or calls to external systems.

A migration may:

  • delete or rewrite data;
  • lock a busy table;
  • break an older application instance during a rolling deployment;
  • add a constraint that existing rows cannot satisfy;
  • change defaults for new rows without fixing old ones;
  • expose data through grants, policies, or an API layer;
  • finish structurally while leaving the wrong data behind.

An agent does not know your production row counts, traffic, deployment order, restore capability, or downtime limits unless you provide evidence. Require it to identify those unknowns instead of guessing.

Database behavior varies. PostgreSQL lock levels and concurrent index restrictions, MySQL implicit commits and online DDL support, SQLite table-rebuild behavior, and ORM transaction rules are not interchangeable. Check the documentation for your deployed versions before approving generated commands. Useful starting points include the official PostgreSQL ALTER TABLE, PostgreSQL CREATE INDEX, MySQL implicit commit, SQLite ALTER TABLE, and Prisma production migration documentation.

1. Inspect the migration system

Use this before asking the agent to create or modify a migration.

Inspect this repository's database and migration system before changing files.

Identify:
- database engine and version assumptions
- ORM, query builder, or migration framework
- schema source of truth
- migration directory and naming/order convention
- available status, creation, apply, validation, and rollback commands
- seed, fixture, and test-database behavior
- how migrations are deployed
- existing backup, restore, and recovery documentation
- tables, views, triggers, policies, functions, indexes, and application code related to [target feature]
- tests that cover the affected behavior

Classify the requested change as low, medium, or high risk. Explain destructive changes, locks, constraints, backfills, deployment ordering, authorization changes, compatibility requirements, and reversibility limits. State whether an expand-contract sequence would be safer.

Return the relevant files, current behavior, related migration history, missing operational facts, risk classification, and verification plan.

Do not modify files, run a migration, connect to production, or print credentials.

This catches repositories where the generated schema, migration history, and deploy command are controlled by different files.

2. Classify a proposed change

Use this shorter prompt when the migration system is already understood but the scope is not.

Classify this proposed database change before writing SQL:

[describe the requested change]

Check for:
- deletion, rename, type conversion, or irreversible transformation
- new NOT NULL, UNIQUE, CHECK, or foreign-key constraints
- defaults, backfills, or data rewrites
- large-table index creation
- trigger, function, view, row-level-security, grant, or policy changes
- old/new application compatibility requirements
- temporary dual-read or dual-write behavior
- downtime, lock, replication, or storage-growth risk
- sensitive or tenant-owned data

Return the risk level, reasoning, facts still needed, safer alternatives, rehearsal requirements, recovery evidence, and approval gates.

Do not write or apply the migration.

The label matters less than the evidence behind it. A small SQL diff can still carry a high operational risk.

3. Design an expand-contract migration

A direct rename or destructive replacement can break old and new application versions while both are running. Expand-contract separates compatibility work from cleanup.

Design an expand-contract sequence for this change:

Current state:
[describe the current table, column, API, and application behavior]

Target state:
[describe the desired state]

Requirements:
- keep the current application version working during expansion
- prefer additive schema changes first
- separate schema expansion, backfill, application cutover, validation, and cleanup
- delay drops and destructive renames until compatibility is verified
- identify whether dual-read or dual-write logic is required
- if dual writing is proposed, define the canonical value, retry behavior, reconciliation, race handling, and cutoff
- include background workers and scheduled jobs in the compatibility plan

Return the staged plan, validation queries, cutover criteria, tests, observability, and rollback or forward-fix options for each stage.

Do not edit files or run commands.

Use this pattern only when the rollout needs a compatibility window. A development-only table with no important data may not need it.

4. Profile existing data before adding constraints

A new constraint can fail if old rows violate it. Generate the queries first, then have a database operator review their cost and execution scope.

Prepare read-only data-profiling queries for this proposed constraint:

[describe the constraint and affected columns]

Measure:
- total affected rows
- NULL or empty values
- duplicate candidate keys
- orphaned foreign-key values
- values outside the proposed CHECK condition
- rows that would fail type conversion
- affected counts by tenant or ownership boundary, when relevant

Requirements:
- generate query text only; do not execute it
- prefer aggregate counts
- include samples only for approved, non-sensitive columns and keep them bounded
- do not use locking clauses or side-effecting functions
- recommend query-plan review, a restricted role, and statement timeout where supported
- explain how each result changes the migration decision
- define the acceptance condition, including any documented exceptions

Do not update, delete, backfill, apply constraints, or expose personal data.

A SELECT can still consume significant resources or call a function with side effects. Treat production profiling as an operation that needs review, not as harmless by definition.

5. Create a bounded backfill plan

Large one-shot updates can cause long transactions, locks, replica lag, or difficult recovery.

Prepare a candidate backfill plan for production review for [table.column or transformation].

Known facts:
- database engine and version: [value]
- migration framework: [value]
- approximate affected rows: [count or unknown]
- traffic and maintenance window: [known details]
- target transformation: [describe]

Requirements:
- if row count, write traffic, or engine behavior is unknown, stop and list the measurements needed
- use stable, unique keyset ordering rather than an unsafe offset loop
- make the operation idempotent and restartable
- define batch progress without logging sensitive row data
- account for writes that happen during the backfill
- define transaction size, throttling, timeouts, and replica-lag limits only from environment evidence
- report rows that cannot be transformed
- keep the final constraint separate until validation passes

Provide the algorithm, draft SQL or implementation, progress tracking, load risks, validation queries, abort conditions, resume procedure, and completion criteria.

Do not run the backfill or connect to production.

Reject plans that invent row counts, claim a universal batch size, or call themselves “production-safe” without workload evidence.

6. Review a generated migration diff

Use this after a migration file exists but before applying it to an important environment.

Review this migration diff as a database safety reviewer.

Check for:
- DROP, TRUNCATE, irreversible DELETE, or unbounded UPDATE statements
- renames represented as drop-and-add
- implicit casts that may fail or lose precision
- constraints without data profiling or backfill
- index choices for foreign keys and new query patterns
- engine-specific index creation restrictions
- long locks, table rewrites, implicit commits, or transaction conflicts
- trigger, function, grant, policy, and API-exposure changes
- framework-generated SQL that has not been inspected
- application compatibility during rollout
- rollback claims that cannot recover data
- missing post-migration checks

Separate blockers, high-risk findings, lower-risk findings, and acceptable parts. Provide required revisions and exact verification queries or commands with environment placeholders.

Do not apply the migration or modify production.

Do not treat an index on every foreign key as a universal rule. Evaluate the engine and the actual join, update, and delete patterns.

7. Rehearse on an isolated database

A rehearsal should use the real migration command against a disposable environment or approved sanitized copy. It does not prove production timing or lock behavior.

Create a planning-only rehearsal runbook for [migration name].

Allowed target: an isolated test database, disposable container, or approved sanitized copy. Production is forbidden.

The runbook should:
1. record the starting migration version or framework state
2. run integrity checks before the change
3. capture bounded pre-migration counts
4. apply the migration with the real deployment command
5. record duration, generated SQL, warnings, and errors
6. run schema and integrity checks afterward
7. run affected application tests
8. verify expected data and authorization behavior
9. restore a fresh baseline before repeating when rollback cannot recreate the original state
10. retain an evidence summary without secrets or personal data

Mark every command that needs project-specific substitution. This prompt is planning-only: do not create a database, restore a snapshot, apply a migration, or run rollback commands.

For example, a Prisma project might rehearse prisma migrate deploy against a disposable database after the operator verifies the connection target. That example does not authorize the command, and it does not make the same procedure correct for Django, Rails, Alembic, Flyway, or another framework.

8. Build a verification matrix

“Migrated successfully” is not a complete result. Define what must be true afterward.

Build a verification matrix for this migration and application change:

[describe the change]

Cover:
- expected migration version, checksum, or framework state when supported
- tables, columns, types, defaults, constraints, indexes, triggers, policies, and grants
- integrity checks supported by the database
- backfill completion and invalid-row handling
- tenant or ownership isolation
- affected create, read, update, and delete behavior
- old/new application compatibility during rollout
- workers, webhooks, reports, caches, and generated clients
- logs, health signals, storage growth, replica lag, and connection pressure
- rollback or forward-fix trigger conditions

For each check, provide what it proves, the command or query, expected result, retained evidence, and severity if it fails.

If traffic can change row counts during verification, define a consistent snapshot, maintenance window, or tolerance instead of assuming exact pre/post equality.

Do not run production commands.

Put the matrix in the pull request or change ticket so reviewers can inspect the data risk alongside the code diff.

9. Plan application and migration deployment order

Schema and code often need a specific release sequence.

Plan the deployment order for this application and database change.

Inputs:
- current application behavior: [describe]
- target behavior: [describe]
- migration stages: [list]
- hosting model: [rolling, serverless, single instance, etc.]
- background workers and scheduled jobs: [list]

Return:
1. pre-deployment checks
2. migration and application release order
3. old/new version compatibility window
4. worker or job coordination
5. cache and generated-client updates
6. health checks after each stage
7. lock, statement-timeout, replica-lag, and storage thresholds where supported
8. stop conditions
9. rollback versus forward-fix decision points
10. cleanup timing

Assume old and new application instances may overlap unless the platform proves otherwise. Do not deploy anything.

This is where an agent should catch code that expects a new column before it exists, or cleanup that starts while an older worker still uses the old schema.

10. Prepare a production runbook without executing it

The last prompt creates a plan for an authorized operator or controlled deployment workflow. It does not grant the coding agent production access.

Prepare a production migration runbook for review. Do not execute it.

Include:
- owner or operator
- exact environment and database identity checks
- current migration state and single-runner or migration-lock behavior
- least-privilege credential requirements without printing secrets
- backup scope, restore procedure, and available restore evidence
- preflight queries and acceptance conditions
- inspected migration SQL and exact command with placeholders
- duration expectations only when rehearsal evidence supports them
- progress, lock, timeout, replica-lag, storage, and connection signals
- post-migration verification matrix and application smoke tests
- stop conditions and rollback or forward-fix decisions
- evidence paths and escalation steps

Mark each step READ-ONLY, ISOLATED WRITE, or PRODUCTION WRITE. Place an explicit human approval gate immediately before the first production write.

Do not connect to production, run the migration, deploy, restore a backup, or send messages. Production execution remains out of scope for this coding agent even after the runbook is approved.

A backup’s existence does not prove recoverability. The operator still needs to understand what it covers, how restoration works, and what evidence exists that the procedure is usable.

Compact migration prompt

For a smaller change, start here:

Inspect the repository and propose the smallest safe migration for [requested change].

Before editing:
- identify the database, migration framework, schema source, related code, tests, and deployment process
- classify destructive, lock, compatibility, constraint, backfill, authorization, and recovery risks
- list unknown production facts instead of guessing

Prefer additive changes when versions may overlap. Profile data before tightening constraints. Keep backfills bounded and restartable. Add tests and a verification matrix. Do not expose sensitive data.

Return the plan, proposed files, migration draft, verification matrix, and operator runbook separately.

You may edit local project files and run isolated tests only after plan approval. Do not connect to production, apply remote migrations, deploy, delete data, restore backups, or send messages.

Before production

Confirm that:

  • the migration was rehearsed against an isolated database;
  • destructive or irreversible steps have explicit approval;
  • old and new application versions can coexist during rollout;
  • backup and restore claims are supported by evidence;
  • data, authorization, and application checks have acceptance conditions;
  • production writes and recovery decisions remain operator-controlled.

Run the broader AI-coded app launch audit checklist and vibe coding deployment checklist before release. The SaaS feedback board guide also shows a worked companion-build migration from local SQLite to hosted Supabase Postgres.

Use the prompts that match the risk of the change. A nullable column on an empty development table does not need the same runbook as a production backfill. Whatever the scope, keep production writes behind explicit approval and accept only checks backed by real output.