Last updated 13 October 2026
Use Claude Code for database migrations
The friction of manual database migrations
Writing database migrations manually creates a significant gap between your application logic and your persistence layer. You often find yourself jumping between your code editor and a SQL terminal to check existing table definitions or column constraints. This constant context switching leads to small but costly errors like typos in column names or mismatched data types that you only discover during the deployment phase. When you use Claude Code, you can bridge this gap by letting the agent examine your current schema and your code changes simultaneously. It uses the Read tool to look at your existing migration files and the Bash tool to query your local development database. This ensures that the SQL it generates is not just syntactically correct but also perfectly compatible with your actual database state.
The agent acts as a direct bridge between your intent and the technical requirements of your database engine. Instead of manually writing out alter table statements and worrying about the exact syntax for adding an index in a specific version of your database, you can describe the change you want in plain language. The agent then performs the necessary research within your repository. It looks at how previous migrations were structured and what naming conventions were used. This approach reduces the mental load of remembering every detail of your schema and allows you to focus on the business logic that necessitates the change in the first place.
Configuring project instructions in CLAUDE.md
To get consistent results across all your migration tasks, you should define your migration standards in the CLAUDE.md file at the root of your repository. This file serves as the primary source of truth for the agent regarding your project conventions and architectural rules. You might specify that all migrations must include a roll back script or that table names should always use the snake-case format. By placing these rules in CLAUDE.md, you ensure that every session started with the claude command follows the same patterns without you needing to repeat yourself. The agent reads this file at the start of every interaction to understand the boundaries of its work and the specific style you expect.
If your project has a specific directory for database logic, you can place a secondary CLAUDE.md file in that subdirectory to provide more focused guidance. This is useful for backend developers working on large repositories where only one part of the tree handles SQL or database interactions. The instructions in the subdirectory apply specifically to the files within it, allowing you to provide more granular details about your ORM or migration framework of choice. When the agent uses the Glob tool to find files, it will respect these layered instructions and prioritize the local rules over the global ones. This setup keeps the main project instructions clean while providing the agent with the specific context it needs to manage your schema changes effectively.
Automating schema inspection with the Bash tool
Before Claude Code can write a new migration, it needs to know the exact current state of your database. You can prompt it to describe a specific table or list all existing constraints by running the claude command in your terminal. Because the agent has access to the Bash tool, it can execute your local database CLI like psql, mysql, or any custom migration tool you have installed. You do not need to manually copy and paste your schema into the prompt or export it to a text file. Instead, you can simply tell the agent to inspect the current state of a specific table and it will run the necessary commands to fetch that metadata. This real-time access ensures the agent is working with the actual state of your environment rather than an outdated version in its memory.
This capability is particularly helpful when you have a complex schema with many foreign keys, triggers, or stored procedures. The agent can use the Grep tool to search through your history of migration files to see how previous changes were implemented and what patterns were followed. By combining the output of live database queries with the history found in your files, the agent builds a comprehensive model of your data structure. This prevents it from suggesting changes that would conflict with existing indexes or violate unique constraints. It provides a layer of safety and intelligence that is hard to achieve with a standard chat interface that cannot interact with your local environment.
Generating and applying migration files
Once the agent understands the current state of your project, you can prompt it to generate a new migration based on a specific feature request. For example, you might ask it to add a column for user preferences that stores a JSON object with a default value. The agent will use the Write tool to create a new file in your migrations directory with the correct timestamp or sequence number required by your framework. It follows the patterns it saw in your existing migration files to ensure the new file fits into your deployment pipeline. You can review the generated SQL or code within the terminal interface before it is finalized to ensure it meets your expectations.
Applying the migration is the next logical step in this automated workflow. You can instruct the agent to run the migration command using its Bash tool, which allows it to see the results of the execution immediately. If the migration fails due to a syntax error or a database constraint violation, the agent sees the error output directly in its session. It can then use the Edit tool to fix the migration file and try the process again. This iterative loop happens entirely within the Claude Code session, saving you from manually switching between windows to fix minor SQL errors or path issues. Once the migration succeeds, you can ask the agent to verify the change by querying the database schema again.
Managing long migrations and context limits
Complex database refactors often result in very long conversations that fill up the context window of the session. As the session grows, the agent might start to lose track of the specific details discussed at the beginning or become less efficient in its processing. You can use the /compact command to summarize the session so far and free up space in the context window. This command summarizes the previous exchanges and keeps the essential information about your schema changes while removing the redundant details. If you are starting a completely new set of migrations for a different feature, the /clear command allows you to start over in the same folder without carrying over any irrelevant history that might confuse the agent.
For developers managing multiple microservices or parallel database tasks, adhdTerminal offers a way to keep these work streams organized. It allows you to run many Claude Code sessions side by side as tiles on a single wall on your macOS or Windows desktop. You can have one tile dedicated to a Postgres migration for your authentication service and another tile handling a schema change in a Redis instance for your caching layer. Each tile on the wall has a colour, a number, and a name, which shows whether it is working, waiting for you, done, or idle. This visual layout prevents you from losing track of which migration is in which state across different repositories and terminal tabs.
Enforcing safety with permission modes
Modifying a database schema requires caution, even in a local development environment. Claude Code offers several permission modes to control how much autonomy the agent has when executing commands or writing files. By default, the agent will ask for your approval before running bash commands or modifying your code. You can cycle through these modes using Shift+Tab inside a session. If you are in a high-stakes situation where you want to be extremely careful, you might switch to the plan mode. In this mode, the agent will describe what it intends to do in detail without actually executing any tools, allowing you to audit its logic before any SQL is written to your disk or any commands are run.
If you are confident in your setup and want to speed up the process for routine tasks, you can adjust the permissions in your settings.json file. This file allows you to specify which tools are allowed to run without a confirmation prompt from you. For instance, you might allow the Read and Glob tools to run freely while keeping the Bash and Write tools under manual control. These settings can be defined globally in your home directory or specifically for a project in the .claude directory. This flexibility allows you to balance speed and safety depending on the complexity of the database migration task and your familiarity with the project.
Verifying migrations with subagents and specialized tools
For large-scale database changes, you can create specialized subagents to handle different parts of the migration process. These subagents are defined as markdown files in the .claude/agents directory and can be tailored with specific instructions for different types of databases. You might create an agent specifically for data validation that runs a series of complex checks after a migration is applied to ensure no data was lost or corrupted. By using the /agents command, you can delegate the task of verification to this specialized subagent. It can even use the WebSearch tool to look up the latest best practices for specific database engines if it encounters an unfamiliar error.
While the agent works on your migrations, you can monitor its progress through the free iPhone app provided by adhdTerminal. The app mirrors your wall of tiles over an end-to-end encrypted link, allowing you to check the status of a long-running migration while you are away from your desk. If the agent hits a point where it needs your input to resolve a schema conflict or if a command fails, you can send the next task or answer its prompt directly from your phone. This mobility ensures that your database tasks keep moving forward even if you need to step away from your computer. The app provides a convenient way to stay connected to your terminal workflow without being tied to your physical workstation.
Tracking costs and session history
Database migrations can involve many iterations and extensive file reading, which contributes to the cost of using an agentic tool. You can use the /cost and /usage commands at any time to see how much you have spent in the current session. This transparency helps you manage your budget and decide when it is time to use the /compact command to reduce the size of the messages being sent to the model. The agent also provides a way to look back at previous work if you need to recall the reasoning behind a specific schema change. By keeping an eye on these metrics, you can maintain a cost-effective workflow while still leveraging the full power of the agent.
If you need to resume a migration task from a previous day, the claude --resume command offers a list of earlier sessions to pick from. This allows you to pick up exactly where you left off with all the previous context and decisions intact. Alternatively, the claude --continue command carries on the most recent session in your current folder, which is ideal for quick follow-up tasks. This is useful when you have a sequence of related migrations and want to maintain the continuity of the conversation without re-explaining the project structure. By managing your sessions effectively, you ensure that the history of your schema changes is preserved and remains accessible whenever you need to revisit a decision.
Questions people ask
How do I handle migrations that require manual data cleanup?
You can use the plan mode to have the agent outline the cleanup steps first. Once you approve the logic, you can switch back to the default mode and have the agent execute the cleanup using the Bash tool. This ensures you have full control over sensitive data modifications before they are applied.
Can the agent handle migrations for multiple different databases at once?
Yes, by using the /mcp command to connect to different database servers or by running multiple sessions in adhdTerminal. Each session can be configured to interact with a different database CLI using its own set of project instructions in CLAUDE.md. This keeps the contexts separate and prevents cross-contamination of schema details.
What if the agent suggests a migration that would break production?
You should always use the /review command or the plan mode to inspect the generated SQL before it is applied. Claude Code respects your project instructions in CLAUDE.md, so you should explicitly list any dangerous operations that are forbidden. The agent is a tool for automation, but the final decision to run a migration always rests with you.
Read next
- Add build instructions to your CLAUDE.md fileImprove project context by adding specific build commands and environment requirements to your CLAUDE.md file for the AI to follow.
- Add common error fixes to CLAUDE.mdImprove project memory by adding a section for common errors and their fixes to your CLAUDE.md configuration file.
- Add custom shell aliases for Claude CodeSpeed up your workflow by creating shell aliases for common Claude Code invocations and project-specific startup commands.
- Add test commands to a CLAUDE.md fileUnderstand how to define specific test runners and environment flags in your CLAUDE.md file so the tool runs the correct test suite.