Coding
AI Prompt for Database Performance
Fix slow database queries with this AI prompt: N+1 detection, eager-loading fixes, index recommendations, and query counts proving improvement.
The prompt
Role: You are a database performance expert who fixes slow data access at the application AND database level. Context: Stack: [STACK]. Symptom: [SYMPTOM, e.g. page runs 120 queries, 2.3s]. Suspect: [SUSPECT]. Code: [CODE] Schema/indexes: [SCHEMA] Task: 1) Diagnose the query pattern: N+1, missing eager loading, SELECT *, missing index, chatty transactions — with evidence from [CODE]. 2) Fix at the application level (eager loading, batching, caching) with code. 3) Fix at the database level if needed (indexes with CREATE INDEX statements). 4) Show how to verify: query count before/after, EXPLAIN for the heavy queries. 5) Set a query-count BUDGET for this operation going forward. Format: Diagnosis with evidence, then app-level fix, then DB-level fix, then verification steps, then the budget. Constraints: Fix the pattern, not just this page — check for the same N+1 elsewhere and say where to look. Every fix needs a before/after measurement. The budget prevents regression.
Variables to fill in
Replace each [variable] in the prompt with your own details:
[STACK] [SYMPTOM] [SUSPECT] [CODE] [SCHEMA]
Example input
STACK=Django/Postgres, SYMPTOM=product page: 120 queries, 2.3s, SUSPECT=N+1 on reviews + images, TABLES=products, reviews, images
How to use this prompt
Count the queries (Django Debug Toolbar, Rails logs) — the number tells the story. Name the suspect pattern; N+1 has a specific signature.
Tips for the best results
- The query count is the headline metric — get it before and after.
- Ask where else the same N+1 pattern lurks in your codebase.
- Set up query-count assertions in tests to catch regressions automatically.
Frequently asked questions
ORM or raw SQL fix?
It diagnoses the query pattern (N+1, missing index, SELECT *) and gives the ORM-level fix plus the SQL-level fix — both, so you learn.
How many queries per page is too many?
There is no magic number, but triple digits signal N+1. The prompt sets a per-operation budget so regressions get caught in tests.