Skip to content

Playbook

Database Optimization With AI Agents, Let the Query Plan Be the Judge

AI can suggest indexes and rewrites in seconds. A safe database optimization workflow starts with a baseline, reads the real query plan, and proves the gain.

The Vibe Father 8 min read
Modern software office with workstations and a presentation display
A collaborative software workspace. Wikimedia Commons Denissalatin CC0 1.0
Share Post to X LinkedIn

An AI agent can produce an index recommendation before you finish describing the slow query. That does not make the recommendation safe. Database tuning is one of the places where a fluent suggestion can create a costly regression, extra write overhead, a lock on a large table, an index that never gets used, a query plan that changes after data grows, or a “fix” that only works on a toy dataset.

The rising interest in database optimization is deserved. The reliable workflow is simple, establish a baseline, inspect the real plan, make one hypothesis, prove the result, and preserve a rollback. Use an agent to accelerate the investigation—not to replace the evidence.

Start with the question, not the index

“Optimize the database” is not an agent task. Begin with one user-visible problem, a dashboard query that times out, a report that slows after a table crosses a threshold, or a write path that holds a lock too long. Capture the exact query shape, representative parameters, current latency, frequency, and the data volume that makes it fail.

Then write a bounded brief

Outcome
- Reduce the p95 latency of <query or endpoint> without changing results.

Ground truth
- Current query and representative parameters
- Current EXPLAIN / EXPLAIN ANALYZE output
- Table sizes, indexes, and relevant write volume

Constraints
- No production DDL without review and an approved rollout window
- Preserve query results and authorization behavior

Definition of done
- Benchmark before and after on representative data
- Explain the plan change
- Include migration, rollback, and validation steps

That is a version of the AI coding task brief tailored to a high-blast-radius surface.

Let the query plan tell you what is happening

PostgreSQL and MySQL both provide EXPLAIN to show how the optimizer intends to execute a statement. PostgreSQL’s documentation emphasizes that the planner chooses among possible plans based on the query and properties of the data, MySQL similarly exposes join order and access choices. The plan is the evidence an agent needs before it suggests an optimization.

Ask the agent to identify, in plain language

  • which table dominates the work,
  • whether the estimate and actual row counts diverge,
  • where filtering, sorting, joining, or aggregation becomes expensive,
  • whether an existing index is usable for the actual predicate and ordering, and
  • which assumption would make the proposed change wrong.

For PostgreSQL, use EXPLAIN (ANALYZE, BUFFERS) only in a safe environment or with a query you understand, because ANALYZE executes the statement. For MySQL, use EXPLAIN and, where appropriate, its execution-analysis tooling. Do not point an eager agent at production and call it observability.

The one-change experiment

Pick the smallest change that tests a specific hypothesis. Maybe it is an index that matches a selective predicate, a rewrite that moves a non-sargable expression, a missing foreign-key index, fresher statistics, or a pagination shape that stops scanning rows it will never return.

Change one thing. Then compare

BeforeAfterQuestion
Representative latencyRepresentative latencyDid the user-visible path improve?
Plan node and row estimatePlan node and row estimateDid the optimizer choose the intended access path?
Rows read and buffers / I/ORows read and buffers / I/ODid we reduce work, not just move it?
Write latency and storageWrite latency and storageWhat did the new index cost?
Result fixtureResult fixtureDid behavior stay correct?

If the gain is not measurable, do not merge it because the model’s explanation sounded clever. Revert it and investigate the next hypothesis.

Where agents are genuinely useful

Agents are excellent at the mechanical parts of an investigation, collecting query shapes, normalizing plan output, finding queries with similar predicates, generating a reproducible benchmark harness, drafting a migration, and explaining an unfamiliar plan node. They can also propose alternatives you might not think to test.

They are poor at declaring that an optimization is safe without the workload data. An LLM has not seen your skewed tenant distribution, your production connection pressure, or the monthly job that writes ten times more data than today’s sample. Let it generate hypotheses, make measurements decide.

Database changes need a stricter definition of done

  1. Correctness the query returns the same authorized result set for representative cases.
  2. Performance the measured target improves on production-shaped data, not only locally.
  3. Cost write overhead, storage, locks, and cache effects were considered.
  4. Rollout the migration is safe for the engine and table size, with an owner and maintenance window where needed.
  5. Recovery the team can roll back or disable the change without guessing.

That is the same verification-first discipline described in our definition-of-done guide, with higher stakes because a database mistake can affect every request at once.

The rule worth remembering

Never merge an AI-suggested index because it looks intuitively right. Merge it because a representative plan and benchmark show that it improves the target workload, the write cost is acceptable, and you can undo it safely. In database work, the query plan is the reviewer who does not care how persuasive the explanation sounded.

Sources

Reader check

Was this article helpful?

One click helps us decide what to research next.

The app behind this research

TheVibeFather is the multi-CLI AI coding harness

You just read field notes from the same team that ships TheVibeFather — the multi-CLI AI coding harness that runs Claude Code, Codex, OpenCode and more with shared memory and a verify gate. Bring your own keys.

Keep reading