Claude Code PostgreSQL Integration

Use Claude Code with PostgreSQL to design normalized schemas, write and optimize SQL, read query plans, plan indexes, and ship migrations with confidence.

By David Iya - Updated 2026-08-27

You already build with Claude Code, but your database work is still manual and risky: you hand-write SQL, guess at indexes, squint at EXPLAIN ANALYZE plans, and hope a migration will not lock a table in production. The PostgreSQL integration closes that gap by letting Claude read your schema, explain slow queries, propose the right index, and plan reversible migrations before anything touches your data.

Before you start

  • Claude Code available in the environment where you work on the database (desktop app or CLI).
  • A running PostgreSQL instance you can reach, whether local, in Docker, or a managed provider.
  • The psql client installed so you can run and verify the SQL Claude suggests.
  • A database connection string or credentials with only the privileges the workflow needs, ideally a read-only role for analysis.
  • The Postgres MCP server configured if you want Claude to inspect the schema and run guarded queries directly.

What it unlocks

Better Schema Design

Describe your domain and let Claude Code propose a normalized table design with sensible primary keys, foreign keys, and data types, then explain the tradeoffs before you commit to it.

Faster SQL Writing

Turn a plain-language requirement into a correct query using joins, CTEs, and window functions, grounded in your real schema rather than a generic template.

Query Plan Analysis

Paste an EXPLAIN ANALYZE plan and get a plain-language read of sequential scans, nested loops, and row estimates so you know exactly where the time goes.

Smarter Indexing

Get index recommendations tied to your actual query patterns, including composite and partial indexes, with a clear note on the write cost each one adds.

Safer Migrations

Plan schema changes as reversible, non-blocking migrations, with the up and down steps ordered so you avoid long locks and can roll back cleanly.

Query Optimization

Rewrite slow queries into faster equivalents by removing redundant scans, fixing bad join order, and replacing patterns that defeat the planner.

Connection and Pooling Guidance

Get help sizing a connection pool, configuring PgBouncer, and avoiding the max-connections errors that appear under load.

Faster Debugging

Give Claude Code the error, the query, and the schema so it can trace a deadlock, permission failure, or type mismatch to its root cause instead of guessing.

Reliable Backups and Restores

Generate the correct pg_dump and pg_restore commands for your case, whether that is a full backup, a single table, or a schema-only snapshot.

Stronger Data Integrity

Add the constraints, foreign keys, and checks that keep bad data out, with Claude explaining what each one enforces and how it affects writes.

How to connect PostgreSQL

1

Confirm PostgreSQL is reachable

Make sure your database is running and you can connect from the machine where Claude Code runs. A quick psql connection is the fastest way to confirm the host, port, and credentials are correct before wiring anything else.

psql "postgresql://user:password@localhost:5432/mydb" -c "SELECT version();"
2

Create a least-privilege role

For analysis and query work, connect Claude Code through a read-only role rather than a superuser. This lets it inspect schemas and run SELECTs while keeping writes and DDL behind a separate, deliberate step.

CREATE ROLE claude_ro LOGIN PASSWORD 'strong-secret'; GRANT CONNECT ON DATABASE mydb TO claude_ro; GRANT USAGE ON SCHEMA public TO claude_ro; GRANT SELECT ON ALL TABLES IN SCHEMA public TO claude_ro;
3

Configure the Postgres MCP server

Add the Postgres MCP server to your Claude Code configuration so it can read the schema and run guarded queries directly. Pass the connection string through an environment variable, never inline in a committed file, and prefer the read-only role for day-to-day analysis.

pip install postgres-mcp
4

Verify the connection from Claude Code

Ask Claude Code to list the tables in the public schema through the MCP server. If it returns your real tables, the connection, credentials, and privileges are all wired correctly.

psql "$DATABASE_URL" -c "\dt"
5

Run a first analysis

Give Claude Code a real query from your app and ask it to run EXPLAIN ANALYZE and summarize the plan. Confirm the output matches the tables you expect before you rely on it for tuning or migrations.

Diagnose and Fix a Slow Query

  1. Connect the database

    Give Claude Code read access to the database through the Postgres MCP server or paste the relevant schema so it has the tables, columns, and existing indexes.

  2. Share the slow query

    Provide the query that is running slowly along with the parameters it is called with in production.

  3. Capture the plan

    Run EXPLAIN (ANALYZE, BUFFERS) on the query and give the full output to Claude Code so it can see actual timing and row counts.

  4. Find the bottleneck

    Ask Claude Code to identify the costly nodes, such as a sequential scan or a bad join order, and explain why the planner chose them.

  5. Apply the fix

    Have Claude Code propose an index or query rewrite, explain the write-cost tradeoff, and generate the exact CREATE INDEX or updated SQL.

  6. Verify the improvement

    Re-run EXPLAIN ANALYZE after the change to confirm the plan improved and the query is faster before shipping it.

What people build with it

Schema Design and Normalization

Describe the entities and relationships in your app and have Claude Code produce a normalized schema with keys, types, and constraints you can review and refine.

Writing Complex Queries

Translate a reporting or feature requirement into SQL that uses the right joins, CTEs, and aggregates against your existing tables.

Reading EXPLAIN ANALYZE

Feed a query plan to Claude Code and get a clear explanation of the costly nodes, bad row estimates, and the single change most likely to help.

Index Strategy

Ask which indexes a set of queries needs, whether a composite or partial index fits better, and what write overhead each index introduces.

Writing Migrations

Turn a schema change into ordered up and down migration steps that avoid long locks and stay reversible if something goes wrong.

Query Optimization

Hand Claude Code a slow query and its plan and have it propose a rewrite or index that removes the sequential scan or bad join order.

Connection Configuration and Pooling

Set up a connection string, size a pool, and configure PgBouncer so your app does not exhaust max_connections under real traffic.

psql Exploration

Learn the psql meta-commands to inspect tables, indexes, and roles, and have Claude Code explain the output of \dt, \d, and \di.

Joins, CTEs and Window Functions

Build advanced queries with multi-table joins, recursive CTEs, and window functions like ROW_NUMBER and RANK, with each part explained.

Data Modeling

Model tricky cases such as many-to-many relationships, soft deletes, and audit trails, and weigh JSONB against relational columns for semi-structured data.

Performance Tuning

Investigate a slow endpoint by tracing its queries, checking for missing indexes and lock contention, and tuning the statements that matter most.

Backups with pg_dump

Generate the exact pg_dump and pg_restore commands for a full backup, a single table, or a schema-only snapshot, and verify the restore works.

Constraints and Foreign Keys

Add primary keys, foreign keys, unique constraints, and check constraints that enforce integrity, with the ON DELETE behavior chosen deliberately.

Debugging Common Errors

Diagnose connection refused, permission denied, deadlocks, and type mismatch errors by walking from the message to the underlying cause.

Diagnosing Index Bloat and Locks

Detect index and table bloat, spot lock contention with pg_locks and pg_stat_activity, and plan a safe REINDEX or VACUUM to recover performance.

Commands & configuration

Connect with psql

psql "postgresql://user:password@localhost:5432/mydb"

Opens an interactive session; use a read-only role for analysis work.

List tables in the current schema

\dt

A psql meta-command; pair with \d table_name to inspect columns and indexes.

Read a query plan with real timings

EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM orders WHERE customer_id = 42;

Feed the full output to Claude Code to locate sequential scans and bad estimates.

Create an index to speed up lookups

CREATE INDEX CONCURRENTLY idx_orders_customer_id ON orders (customer_id);

CONCURRENTLY avoids locking the table for writes while the index builds.

Create a table with constraints

CREATE TABLE orders (id BIGSERIAL PRIMARY KEY, customer_id BIGINT NOT NULL REFERENCES customers(id) ON DELETE CASCADE, total NUMERIC(10,2) NOT NULL CHECK (total >= 0), created_at TIMESTAMPTZ NOT NULL DEFAULT now());

Ask Claude Code to justify each type, key, and constraint before you run it.

Back up the database with pg_dump

pg_dump -Fc -f mydb.dump "postgresql://user:password@localhost:5432/mydb"

The custom format (-Fc) restores with pg_restore and supports selective table restores.

Prompts to steal

Design a normalized schema

I am building an application with these entities and relationships: [describe them]. Design a normalized PostgreSQL schema. Give me the CREATE TABLE statements with primary keys, foreign keys, appropriate data types, and constraints, and explain the tradeoffs of any normalization or denormalization decision you make.

Review my schema for problems

Here is my current PostgreSQL schema. Review it for design problems: missing constraints, weak or missing foreign keys, questionable data types, columns that should be normalized, and anything that will cause pain as the data grows. List findings by severity and suggest concrete fixes.

Write a complex query

Using this schema, write a PostgreSQL query that does the following: [describe the result you want]. Use joins, CTEs, or window functions where appropriate, explain how the query works step by step, and note any indexes it relies on to run efficiently.

Explain an EXPLAIN ANALYZE plan

Here is the output of EXPLAIN (ANALYZE, BUFFERS) for a query. Explain the plan in plain language: which nodes are expensive, where the time is actually spent, whether the row estimates are accurate, and the single change most likely to make it faster.

Optimize a slow query

This query is slow. Here is the query, the schema of the tables involved, the existing indexes, and the EXPLAIN ANALYZE output. Identify why it is slow and propose a fix, either an index or a rewrite. Show the exact SQL and explain the tradeoff, including any write cost an index adds.

Recommend indexes for these queries

Here are the queries my application runs most often and the relevant table schemas. Recommend the indexes that would speed them up. For each index, give the CREATE INDEX statement, say whether a composite or partial index is better, and explain the write overhead it introduces.

Plan a safe migration

I need to make this schema change: [describe it]. Write a PostgreSQL migration with clear up and down steps. Order the operations so they avoid long table locks on a production database, use CREATE INDEX CONCURRENTLY where relevant, and make sure the migration is fully reversible.

Diagnose a deadlock

My application is hitting deadlocks in PostgreSQL. Here are the queries involved and the error message. Explain how the deadlock happens, which lock ordering causes it, and how to change the transactions or query order to prevent it without weakening correctness.

Fix connection refused

I am getting a connection refused error when connecting to PostgreSQL with this connection string. Walk me through the likely causes in order, from the server not running to the wrong host, port, pg_hba.conf rules, and listen_addresses, and tell me exactly how to check each one.

Resolve max_connections errors

My application is failing with a too many clients error from PostgreSQL. Explain why this happens, how to size a connection pool correctly for my workload, and how to set up PgBouncer in transaction mode so the app stops exhausting max_connections.

Model a tricky relationship

I need to model this in PostgreSQL: [describe a many-to-many relationship, soft deletes, or an audit trail]. Show the table design, explain whether to use a join table, JSONB, or another approach, and describe the tradeoffs for query performance and data integrity.

Write window function queries

Using this schema, write PostgreSQL queries that use window functions to do the following: [describe the ranking, running total, or per-group calculation you need]. Explain how PARTITION BY and ORDER BY affect the result and how the window frame is evaluated.

Add the right constraints

Here is a table definition. Add the constraints it should have to protect data integrity: primary key, foreign keys with a deliberate ON DELETE action, unique constraints, and check constraints. Explain what each constraint enforces and how it affects inserts and updates.

Build a pg_dump backup plan

I want a reliable backup strategy for this PostgreSQL database. Give me the pg_dump commands for a full backup, a single-table backup, and a schema-only snapshot, explain when to use the custom format versus plain SQL, and show the matching pg_restore commands with a way to verify the restore.

Investigate index bloat

I suspect index or table bloat is slowing down my PostgreSQL database. Show me the queries to measure bloat and dead tuples, explain how to read the results, and recommend whether to run VACUUM, VACUUM FULL, or REINDEX CONCURRENTLY, including the locking implications of each.

Diagnose lock contention

Queries are hanging and I think there is lock contention in PostgreSQL. Show me the queries against pg_locks and pg_stat_activity to find blocking and blocked sessions, explain how to read the output, and recommend how to resolve the contention safely.

Fix a type mismatch error

I am getting a type mismatch or invalid input syntax error from PostgreSQL. Here is the query and the error. Explain what type PostgreSQL expected versus what it received, where the implicit cast is failing, and how to fix it with an explicit cast or a schema change.

Tune a slow reporting endpoint

This application endpoint is slow and it runs these PostgreSQL queries. Trace which query is the bottleneck, check for missing indexes and lock contention, and propose the smallest set of changes, whether indexes, rewrites, or caching, that will make the endpoint fast.

Resolve a migration conflict

Two migrations conflict or a migration failed halfway and left the schema in an inconsistent state. Here is the migration history and the current schema. Explain how to reconcile them safely, whether to roll forward or back, and give me the exact SQL to bring the database to a known good state.

Fix an encoding or collation issue

I am seeing encoding or collation errors in PostgreSQL, such as invalid byte sequence or unexpected sort order. Explain the difference between the database encoding, client encoding, and collation, identify which one is wrong here, and tell me how to fix it safely for existing data.

Recommended MCP servers

  • Postgres MCP Pro (crystaldba/postgres-mcp)

    The actively maintained Postgres MCP server. It exposes schema inspection, EXPLAIN plan analysis, index tuning recommendations, database health checks, and configurable read-only or read/write SQL execution, which makes it the best fit for query optimization and tuning work.

  • Reference Postgres MCP Server (archived)

    Anthropic's original read-only reference server. It can list tables, inspect schemas, and run SELECT queries, but it was deprecated and archived in 2025 with a known SQL-injection weakness, so treat it as a learning example and prefer the crystaldba server for real use.

Skills worth having

  • Schema Design

    Turn a domain description into a normalized PostgreSQL schema with the right keys, types, and constraints.

  • Query Optimization

    Rewrite slow queries and read EXPLAIN ANALYZE plans to remove sequential scans and bad join order.

  • Index Strategy

    Recommend composite and partial indexes tied to real query patterns and their write-cost tradeoffs.

  • Migration Planning

    Plan reversible, non-blocking migrations with ordered up and down steps that avoid long locks.

  • SQL Writing

    Compose correct queries using joins, CTEs, and window functions grounded in your actual schema.

  • Performance Tuning

    Investigate slow endpoints by tracing queries, spotting lock contention, and fixing the statements that matter.

  • Backup and Restore

    Generate correct pg_dump and pg_restore commands and verify that a restore actually works.

  • Data Integrity

    Add foreign keys, unique constraints, and check constraints that keep bad data out of the database.

Troubleshooting

Keep it safe

  • Connect with a least-privilege role. Give Claude Code a read-only role for analysis and keep writes and DDL behind a separate, deliberate step rather than connecting as a superuser.
  • Never paste connection strings or credentials into prompts. Reference the database by name and keep the password and host in an environment variable or secrets manager.
  • Keep the connection string out of the repository. Store DATABASE_URL as a secret, add local env files to .gitignore, and rotate the credential if it is ever exposed.
  • Review every generated migration before running it on production. Read the up and down steps, confirm they avoid long locks, and test them on a copy of the data first.
  • Guard against destructive SQL. Prefer read-only MCP access for analysis, and require an explicit human confirmation before any DROP, TRUNCATE, or unbounded UPDATE or DELETE runs.
  • Back up before schema changes. Take a pg_dump snapshot before a migration or bulk change so you can restore cleanly if something goes wrong.

PostgreSQL + Claude Code: FAQ

What is the Claude Code PostgreSQL integration?

It is a workflow that lets Claude Code work directly with your PostgreSQL database. Claude Code can read your schema, write and optimize SQL, interpret EXPLAIN ANALYZE plans, recommend indexes, and plan migrations, using your real database as the source of truth. It enhances your existing database workflow rather than replacing your judgement over what runs against production.

How do I connect Claude Code to PostgreSQL?

The most capable path is the Postgres MCP server. Install the crystaldba/postgres-mcp server, add it to your Claude Code configuration, and pass your connection string through an environment variable, ideally for a read-only role. Once connected, Claude Code can list tables, inspect schemas, and run guarded queries. You can also work manually by pasting your schema and query plans into a prompt.

Can Claude Code write and optimize SQL?

Yes. Claude Code can turn a plain-language requirement into a correct query using joins, CTEs, and window functions grounded in your schema. For optimization, give it the slow query, the table schemas, the existing indexes, and the EXPLAIN ANALYZE output, and it will propose an index or rewrite and explain the tradeoff so you can decide with evidence.

Can Claude Code read query plans from EXPLAIN ANALYZE?

Yes. Paste the output of EXPLAIN (ANALYZE, BUFFERS) and Claude Code will explain the plan in plain language: which nodes are expensive, whether the row estimates are accurate, where the time is actually spent, and the single change most likely to make the query faster.

Can Claude Code help with database migrations?

Yes. Describe the schema change and Claude Code will write a migration with clear up and down steps, order the operations to avoid long table locks, use CREATE INDEX CONCURRENTLY where relevant, and keep the migration reversible. Always review the generated migration and test it on a copy of the data before running it in production.

Which Postgres MCP server should I use with Claude Code?

Use the actively maintained crystaldba/postgres-mcp server, also known as Postgres MCP Pro. It supports schema inspection, EXPLAIN plan analysis, index tuning, health checks, and configurable read-only or read/write access. Anthropic's original reference Postgres server was deprecated and archived in 2025 with a known SQL-injection weakness, so treat it as a learning example only.

Can Claude Code recommend indexes?

Yes. Give Claude Code your most frequent queries and the relevant table schemas and it will recommend the indexes that speed them up, including composite and partial indexes. For each one it gives the CREATE INDEX statement and explains the write overhead the index adds, so you can weigh read speed against write cost.

Is it safe to give Claude Code access to my production database?

It is safe if you keep control of privileges. Connect through a read-only role for analysis, keep credentials in environment variables or a secrets manager rather than in prompts, and require explicit confirmation before any destructive statement runs. Review every generated migration and take a pg_dump backup before schema changes so you can always roll back.

Go deeper

More integrations

Build Better Database Workflows With Claude Code

Join Claude Code Club to access practical tutorials, prompts, skills, MCP guides, workflows, templates, and real builds designed to help you get more from Claude Code and PostgreSQL.

Related: what is Claude Code, glossary, and use cases.