Claude Code Database Guide
Claude Code and databases
Claude Code can query databases, write migrations, design schemas, generate ORM models, and debug SQL. It is not a database GUI. It is a terminal-based coding agent that happens to be very good at database work because it can read your schema, understand your ORM, and execute queries directly.
The key is knowing how to connect Claude Code to your database. There are three approaches: MCP database servers (best), direct CLI commands (good), and ORM-aware file editing (always available).
MCP database servers
The most powerful approach is connecting Claude Code to your database through an MCP server. MCP (Model Context Protocol) lets Claude call external tools directly, and there are database servers for most popular databases.
Turso / LibSQL
Turso is an edge SQLite database. The MCP server gives Claude direct SQL access:
{
"mcpServers": {
"turso": {
"command": "npx",
"args": ["-y", "@anthropic/turso-mcp"],
"env": {
"TURSO_DATABASE_URL": "libsql://your-db.turso.io",
"TURSO_AUTH_TOKEN": "your-token"
}
}
}
}
Once configured, Claude can run queries directly:
Query the users table for all active subscriptions created this month
Claude translates your natural language into SQL, executes it through the MCP server, and returns formatted results. No copying and pasting queries between tools.
PostgreSQL
For Postgres, use a Postgres MCP server:
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": ["-y", "@anthropic/postgres-mcp"],
"env": {
"DATABASE_URL": "postgresql://user:pass@host:5432/dbname"
}
}
}
}
Same workflow. Ask Claude to query, and it builds and runs the SQL directly against your Postgres instance.
SQLite
For local SQLite databases, Claude can use the Bash tool directly:
Run: sqlite3 database.db "SELECT * FROM orders WHERE status = 'pending'"
No MCP server needed for local SQLite. Claude just executes the command and reads the output.
Direct CLI database access
Even without MCP servers, Claude Code can interact with databases through CLI tools it runs via Bash:
# PostgreSQL
psql -h localhost -U postgres -d myapp -c "SELECT count(*) FROM users"
# MySQL
mysql -u root -p mydb -e "SHOW TABLES"
# SQLite
sqlite3 app.db ".schema users"
# MongoDB
mongosh --eval "db.users.find({active: true}).count()"
Claude knows all of these CLI tools. Tell it which database you are using and it will pick the right command. The tradeoff compared to MCP is that each query is a separate Bash tool call, which uses more context tokens. MCP servers are purpose-built for repeated database interaction.
Schema design with Claude Code
Claude excels at schema design because it can hold your entire data model in context while reasoning about relationships, indexes, and constraints.
A typical workflow:
Describe your domain. "We need tables for users, teams, and team memberships. Users can belong to multiple teams. Teams have an owner who is also a user."
Claude generates the schema:
CREATE TABLE users (
id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),
email TEXT UNIQUE NOT NULL,
name TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE teams (
id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),
name TEXT NOT NULL,
owner_id TEXT NOT NULL REFERENCES users(id),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE team_memberships (
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
team_id TEXT NOT NULL REFERENCES teams(id) ON DELETE CASCADE,
role TEXT NOT NULL DEFAULT 'member',
joined_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (user_id, team_id)
);
CREATE INDEX idx_memberships_team ON team_memberships(team_id);
CREATE INDEX idx_memberships_user ON team_memberships(user_id);
- Iterate. "Add a soft delete column to users and filter it in the membership queries."
Claude modifies the schema and updates all dependent queries. Because it sees the full picture, it catches cascading changes that manual editing misses.
Writing database migrations
Migrations are where Claude Code saves the most time. Instead of writing migration files manually, you describe what needs to change and Claude generates the migration.
With Drizzle ORM
If your project uses Drizzle, Claude can:
- Read your existing schema files in
drizzle/schema/ - Modify the TypeScript schema
- Generate the migration SQL with
npx drizzle-kit generate - Apply it with
npx drizzle-kit migrate(or direct SQL for environments where the migration journal is out of sync)
Add a "subscription_tier" column to the users table.
It should be an enum: free, pro, enterprise. Default to free.
Claude edits the schema file, runs the generator, and you have a clean migration ready to review.
With Prisma
Same pattern with Prisma:
- Claude reads
prisma/schema.prisma - Modifies the schema
- Runs
npx prisma migrate dev --name add-subscription-tier - Updates the Prisma client
Raw SQL migrations
For projects without an ORM, Claude generates numbered migration files:
-- 0012_add_subscription_tier.sql
ALTER TABLE users ADD COLUMN subscription_tier TEXT NOT NULL DEFAULT 'free';
CREATE INDEX idx_users_tier ON users(subscription_tier);
Claude names them consistently with your existing migration numbering and handles both up and down migrations when your framework requires it.
ORM integration
Claude Code understands every major ORM. When it reads your codebase, it picks up which ORM you use and writes code accordingly:
Drizzle
const activeUsers = await db
.select()
.from(users)
.where(eq(users.status, 'active'))
.orderBy(desc(users.createdAt));
Prisma
const activeUsers = await prisma.user.findMany({
where: { status: 'active' },
orderBy: { createdAt: 'desc' },
});
Knex
const activeUsers = await knex('users')
.where('status', 'active')
.orderBy('created_at', 'desc');
Tell Claude what you need in plain language and it writes the query using your project's ORM. It reads your schema types, so the generated code matches your actual table structure.
Querying and analysis
One of the strongest use cases is ad-hoc querying and data analysis. Instead of opening a database GUI, switching contexts, writing SQL, and interpreting results, you stay in the terminal:
How many users signed up this week compared to last week?
What are the top 10 products by revenue this month?
Show me all orders with a total over $500 that haven't shipped.
Claude writes the query, runs it (via MCP or CLI), and presents the results with context. It can spot anomalies, calculate percentages, and suggest follow-up queries based on what it finds.
For recurring queries, Claude can write them as scripts or saved views so you do not repeat yourself.
Database debugging
When something goes wrong, Claude can diagnose database issues:
- Slow queries: "This query takes 3 seconds. Why?" Claude reads the query, checks for missing indexes, suggests optimizations, and can run
EXPLAIN ANALYZEto confirm. - Data integrity: "Are there any orphaned records in team_memberships?" Claude writes and runs the validation query.
- Connection issues: "The app can't connect to the database." Claude checks environment variables, connection strings, and network configuration.
- Migration failures: "Migration 0015 failed halfway through." Claude reads the error, checks the migration state, and generates a fix.
Safety and permissions
Database operations are inherently dangerous. Claude Code has permission controls that protect against accidental damage:
- Bash permissions control which commands Claude can run. You can restrict database CLI access:
{
"permissions": {
"allow": ["Bash(sqlite3:*)"],
"deny": ["Bash(psql:DROP*)"]
}
}
MCP server scoping can limit what the database server exposes. Some MCP servers support read-only modes.
Hook-based guards can intercept dangerous operations before they execute. A PreToolUse hook could block any query containing
DROP TABLEorTRUNCATE.
Always use a read-only connection for exploratory queries. Save write access for deliberate operations like migrations that you review before running.
Setting up your database workflow
Here is the recommended setup, from simplest to most powerful:
Level 1 -- CLI access (no setup required):
Claude uses sqlite3, psql, or mysql via Bash. Works immediately if the CLI tools are installed.
Level 2 -- MCP server (5-minute setup):
Add a database MCP server to .mcp.json. Claude gets native query access with better token efficiency and richer results.
Level 3 -- Full integration (Claudify):
MCP database servers plus custom commands for common operations (/db-migrate, /db-seed, /db-backup), hooks that prevent destructive queries in production, and skills that encode your schema conventions. This is where Claudify shortcuts weeks of manual configuration.
FAQ
Can Claude Code access a production database?
Yes, if you provide the connection credentials via MCP server config or environment variables. However, you should always use a read-only replica or read-only user for production querying. Write access to production should be gated behind explicit confirmation and limited to migration operations. Use hooks to enforce this boundary.
Which databases does Claude Code support?
Claude Code works with any database that has a CLI tool or an MCP server. This includes PostgreSQL, MySQL, SQLite, Turso/LibSQL, MongoDB, Redis, DynamoDB (via AWS CLI), Supabase, PlanetScale, and Neon. If you can query it from a terminal, Claude can use it.
How does Claude Code handle database credentials?
Database credentials go in your .mcp.json file (for MCP servers) or .env files (for CLI access). Claude reads the MCP config at startup. Never hardcode credentials in your CLAUDE.md or commit them to version control. Keep .mcp.json in your .gitignore and use environment variables or secret managers for production credentials.
Next steps
Start with the CLI approach to see how Claude handles your database. Add an MCP server when you want better token efficiency and richer query results. For a complete setup with database hooks, migration commands, and schema skills pre-configured, check out Claudify.
Get Claudify -- Database workflows, 21 commands, and 9 agents. Installed in one command.
More like this
Ready to upgrade your Claude Code setup?
Get Claudify