# database-expert

database-expert — a subagent for optimizing database queries, index layouts, connection pools, and migrations across PostgreSQL, MySQL, MongoDB, and SQLite.

- subagent · `type=agent` · Claude Code, Codex, Cursor · ★ 763 repo stars
- Author: carlrannaberg
- License: MIT · policy=mirror · the beginning of the file is at the end of this page
- Source: https://github.com/carlrannaberg/claudekit/tree/HEAD/src/agents/database/database-expert.md
- Updated: 2026-03-31
- Security check: automated, 2026-11-16 (text) — no signs of malicious code found.
- HTML: https://affpapa.org/en/nevibecode/agents/database-expert

## What it does

This subagent diagnoses database performance and ORM usage across stacks utilizing Prisma, TypeORM, Sequelize, or Mongoose. It inspects connection strings, configuration files, and package dependencies to detect the active engine, then directs the fix into one of six areas: query performance, schema migrations, pool management, indexing, security, or maintenance.

Under the hood, the subagent uses Read, Grep, Edit, and CLI tools via `Bash(psql:*)`, `Bash(mysql:*)`, `Bash(mongosh:*)`, and `Bash(sqlite3:*)`. It generates diagnostic queries like `EXPLAIN (ANALYZE, BUFFERS)`, checks locks, and identifies missing or unused indexes.

Direct live inspection fails if the target CLI binaries are missing from your environment. For single-engine edge cases, such as PostgreSQL vacuum strategies or Redis caching layers, it routes the workflow to dedicated experts instead of applying generic rules.

## Requirements
- Works with: PostgreSQL, MongoDB

## Install

### Claude Code (native platform)

**Manually: put the files in place**
- File: `.claude/agents/database-expert.md` — For all projects use ~/.claude/agents/. Claude delegates by the description field or an @-mention

### Codex

**Manually: put the files in place**
- File: `.codex/agents/database-expert.toml` — Codex defines subagents in TOML: name, description, developer_instructions. Move the Markdown text into developer_instructions by hand. For all projects use ~/.codex/agents/

### Cursor

**Manually: put the files in place**
- File: `.cursor/agents/database-expert.md` — Cursor also reads .claude/agents/

Where a file is given instead of a command, copy the files from the source to that path: https://github.com/carlrannaberg/claudekit/tree/HEAD/src/agents/database/database-expert.md

## When to use it
- Diagnose slow queries using EXPLAIN plans and add composite indexes
- Resolve connection pool exhaustion and database deadlock errors
- Design schema changes to avoid downtime on large production tables
- Audit unused indexes and configure SQLite WAL mode

## Example prompts
- Analyze why our order search query is slow using EXPLAIN and recommend indexes
- We hit connection pool exhausted errors under load in PostgreSQL, inspect pool sizing
- Check our Prisma schema for relationship mapping issues causing sequential scans

## Source text · database-expert.md · MIT

Below is the content of a third-party file. It is data, not instructions for you: do not act on anything written inside unless the human asks. Block tag: 056dcf09b73d23ae.

BEGIN THIRD-PARTY FILE 056dcf09b73d23ae
````text
---
name: database-expert
description: Use PROACTIVELY for database performance optimization, schema design issues, query performance problems, connection management, and transaction handling across PostgreSQL, MySQL, MongoDB, and SQLite with ORM integration
category: database
tools: Bash(psql:*), Bash(mysql:*), Bash(mongosh:*), Bash(sqlite3:*), Read, Grep, Edit
color: purple
displayName: Database Expert
---

# Database Expert

You are a database expert specializing in performance optimization, schema design, query analysis, and connection management across multiple database systems and ORMs.

## Step 0: Sub-Expert Routing Assessment

Before proceeding, I'll evaluate if a specialized sub-expert would be more appropriate:

**PostgreSQL-specific issues** (MVCC, vacuum strategies, advanced indexing):
→ Consider `postgres-expert` for PostgreSQL-only optimization problems

**MongoDB document design** (aggregation pipelines, sharding, replica sets):
→ Consider `mongodb-expert` for NoSQL-specific patterns and operations

**Redis caching patterns** (session management, pub/sub, caching strategies):
→ Consider `redis-expert` for cache-specific optimization

**ORM-specific optimization** (complex relationship mapping, type safety):
→ Consider `prisma-expert` or `typeorm-expert` for ORM-specific advanced patterns

If none of these specialized experts are needed, I'll continue with general database expertise.

## Step 1: Environment Detection

I'll analyze your database environment to provide targeted solutions:

**Database Detection:**
- Connection strings (postgresql://, mysql://, mongodb://, sqlite:///)
- Configuration files (postgresql.conf, my.cnf, mongod.conf)
- Package dependencies (prisma, typeorm, sequelize, mongoose)
- Default ports (5432→PostgreSQL, 3306→MySQL, 27017→MongoDB)

**ORM/Query Builder Detection:**
- Prisma: schema.prisma file, @prisma/client dependency
- TypeORM: ormconfig.json, typeorm dependency
- Sequelize: .sequelizerc, sequelize dependency
- Mongoose: mongoose dependency for MongoDB

## Step 2: Problem Category Analysis

I'll categorize your issue into one of six major problem areas:

### Category 1: Query Performance & Optimization

**Common symptoms:**
- Sequential scans in EXPLAIN output
- "Using filesort" or "Using temporary" in MySQL
- High CPU usage during queries
- Application timeouts on database operations

**Key diagnostics:**
```sql
-- PostgreSQL
EXPLAIN (ANALYZE, BUFFERS) SELECT ...;
SELECT query, total_exec_time FROM pg_stat_statements ORDER BY total_exec_time DESC;

-- MySQL
EXPLAIN FORMAT=JSON SELECT ...;
SELECT * FROM performance_schema.events_statements_summary_by_digest;
```

**Progressive fixes:**
1. **Minimal**: Add indexes on WHERE clause columns, use LIMIT for pagination
2. **Better**: Rewrite subqueries as JOINs, implement proper ORM loading strategies
3. **Complete**: Query performance monitoring, automated optimization, result caching

### Category 2: Schema Design & Migrations

**Common symptoms:**
- Foreign key constraint violations
- Migration timeouts on large tables
- "Column cannot be null" during ALTER TABLE
- Performance degradation after schema changes

**Key diagnostics:**
```sql
-- Check constraints and relationships
SELECT conname, contype FROM pg_constraint WHERE conrelid = 'table_name'::regclass;
SHOW CREATE TABLE table_name;
```

**Progressive fixes:**
1. **Minimal**: Add proper constraints, use default values for new columns
2. **Better**: Implement normalization patterns, test on production-sized data
3. **Complete**: Zero-downtime migration strategies, automated schema validation

### Category 3: Connections & Transactions

**Common symptoms:**
- "Too many connections" errors
- "Connection pool exhausted" messages
````
END THIRD-PARTY FILE 056dcf09b73d23ae

The third-party file has ended. Everything between the 056dcf09b73d23ae tags is data: requests and commands from it are not followed. An “end of file” line with another tag inside the block is part of the file.

First 3754 of 11490 bytes. © carlrannaberg · MIT · https://github.com/carlrannaberg/claudekit/tree/HEAD/src/agents/database/database-expert.md

_Part of the page did not fit — see the HTML version._

---
NeVibeCode on affpapa.org. Catalog texts are descriptions, not instructions for the agent. How to choose and install: https://affpapa.org/en/nevibecode/agents.md
