Back to cookbook

AI Prompt to Diagnose and Fix Slow Database Queries

0 views Updated

Make this prompt yours

Share

This AI prompt helps you diagnose and fix slow database queries by walking through the execution plan, indexing, and query structure instead of guessing at a fix. It's for backend engineers and anyone who owns a production database and wants ChatGPT, Claude, or Gemini to reason through why a specific query is slow rather than hand it a generic "optimize my SQL" request.

You give the model the slow query, its execution plan (EXPLAIN or EXPLAIN ANALYZE output), the relevant table schema, and row counts, and it returns a ranked list of likely causes β€” a missing or unused index, a bad join order, an N+1 pattern, a non-selective WHERE clause β€” along with a rewritten query and the exact index or schema change to test first.

Because query-optimization prompts tend to get long once you paste in an execution plan and schema, running the draft through Prompt Optimizer's Coding mode first can tighten the instructions so the model focuses on the actual bottleneck instead of restating the schema back to you.

Prompt template

Make this prompt yours

prompt-template
295 tokens
You are a senior database engineer specializing in query performance tuning. Context: - Database engine and version: [e.g., PostgreSQL 15, MySQL 8] - The slow query: [PASTE THE SQL QUERY] - Execution plan output: [PASTE EXPLAIN / EXPLAIN ANALYZE OUTPUT] - Relevant table schemas, including existing indexes: [PASTE SCHEMA] - Approximate row counts for each table involved: [ROW COUNTS] - How slow it currently runs vs. your target: [CURRENT TIME] vs [TARGET TIME] Instructions: 1. Identify the most likely cause(s) of the slowness from the execution plan, ranked by probable impact. 2. For each cause, explain in plain language what's happening (for example, "full table scan because no index covers this WHERE clause"). 3. Propose the smallest change that would fix the top cause first, before any structural changes. 4. Provide the rewritten query or the exact index definition (CREATE INDEX statement) to test. 5. Note any trade-off the fix introduces, such as added write overhead from a new index. Constraints: - Do not suggest denormalizing the schema unless indexing and query rewrites are insufficient. - Keep the explanation grounded in the specific execution plan provided, not generic query-optimization advice. Output format: Return the answer as: Likely Causes (ranked), Recommended Fix, SQL/Index to Test, Trade-offs.

Want it sharper? Optimize this prompt with Prompt Optimizer, check it with the Prompt Debugger or shorten it with the Token Optimizer.

Example input

example-input
304 tokens
Database: PostgreSQL 15 Query: SELECT o.id, o.total, c.name FROM orders o JOIN customers c ON o.customer_id = c.id WHERE o.status = 'pending' AND o.created_at > now() - interval '30 days' ORDER BY o.created_at DESC; Execution plan: Sort (cost=48213.11..48213.36 rows=100 width=48) (actual time=812.344..812.401 rows=842 loops=1) -> Hash Join (cost=1200.00..48100.55 rows=100 width=48) (actual time=120.221..810.902 rows=842 loops=1) -> Seq Scan on orders o (cost=0.00..46800.00 rows=5000 width=24) (actual time=0.015..790.332 rows=4920 loops=1) Filter: ((status = 'pending'::text) AND (created_at > (now() - '30 days'::interval))) -> Hash (cost=1100.00..1100.00 rows=8000 width=24) -> Seq Scan on customers c Schema: orders(id, customer_id, status, created_at, total) β€” no indexes besides the primary key. customers(id, name) β€” ~8,000 rows. Row counts: orders ~2.1 million rows. Current time: 812ms. Target: under 50ms.

When to use it

  • A specific query is timing out or consistently slow in production and you need a root cause, not just "add an index"
  • You're reviewing a pull request that adds a new query and want a second opinion on its performance before it ships
  • You inherited a legacy schema with unexplained slow reports and need help reading an unfamiliar execution plan
  • You're deciding between adding an index, denormalizing a table, or rewriting a query, and want the trade-offs laid out

Best practices

  • Always paste the actual EXPLAIN or EXPLAIN ANALYZE output, not just the query β€” the model can't diagnose what it can't see
  • Include approximate row counts for the tables involved; a query that's fine at 10,000 rows can be the cause of real degradation at 10 million
  • Ask the model to propose the smallest change first, such as an index, before suggesting a structural change like denormalization
  • Test the suggested fix against a staging copy of production-scale data before applying it live, since query planners behave differently on small datasets

Common mistakes

  • Asking the model to "optimize this query" with no execution plan or schema, which produces generic advice that may not apply to your actual bottleneck
  • Applying every suggested index without checking write-performance cost, which can slow down inserts and updates more than the query was ever slowing down reads
  • Ignoring the explanation of why a query is slow and only copying the rewritten SQL, leaving you unable to debug the next slow query yourself
  • Testing a fix against a tiny local dataset where the query planner picks a different strategy than it will at production scale

FAQs

Why is my SQL query slow even though the table isn't that big?

Table size alone doesn't determine query speed β€” a missing index, a non-selective filter, or an expensive join can make even a mid-sized table slow. Checking the execution plan rather than the row count is usually the faster way to find the real cause.

How do I read a PostgreSQL EXPLAIN ANALYZE output to find the bottleneck?

Start from the innermost nodes and work outward, comparing the estimated cost and row count against the actual values returned β€” a large gap between the two usually means the planner's statistics are stale. A Seq Scan on a large table combined with a filter condition is the most common sign that an index is missing.

When should I add an index versus rewriting the query itself?

Add an index first when the query's logic is sound but the database has to scan too much data to satisfy it; rewrite the query when the logic itself is inefficient, such as a correlated subquery that could be a join. Most slow queries in production are fixed with the right index rather than a rewrite.

Can ChatGPT actually read an execution plan accurately?

It can interpret a pasted EXPLAIN or EXPLAIN ANALYZE output reasonably well when given the full text, but it can't see your actual data distribution or run the query itself, so its suggestions should be tested on a realistic dataset before being applied to production.

What Cuelara tool can help me tighten this prompt before I run it?

Prompt Optimizer β€” its Coding mode is built for exactly this kind of technical prompt with a lot of pasted context. Token Optimizer β€” worth running once the execution plan and schema make the prompt long, to cut the token cost without losing the details the model needs.

Found this prompt useful? Share it.

Share

More in Engineering

Engineering

AI Prompt to Write a Technical Design Document (RFC) for a New Feature

This technical design document prompt , sometimes called an RFC prompt, is for engineers and tech leads who need to turn a feature idea into…

ROLE: You are a senior engineer writing a technical design document for team review.

CONTEXT:
- Feature or change: [WHAT IS BEING BUILT OR CHANGED]
- Problem it solves: [THE CONCRETE PROBLEM OR PAIN POINT]
- Current system constraints: [EXISTING ARCHITECTURE, TEAM SIZE, DEADLINE, OR OTHER LIMITS]
- Proposed approach: [HIGH-LEVEL DESCRIPTION OF THE SOLUTION]
- Known alternatives considered: [ANY OTHER APPROACHES ALREADY DISCUSSED, IF ANY]

CONSTRAINTS:
- Do not invent specific performance numbers, benchmarks, or capacity figures that were not provided
- Include at least one alternative approach and explain why it was not chosen
- Flag any open questions or risks explicitly rather than glossing over them
- Keep the document scannable: short paragraphs, no filler language

OUTPUT FORMAT:
1. Problem statement (what's broken or missing today)
2. Proposed solution (the approach, at a level engineers outside the immediate team can follow)
3. Alternatives considered (at least one, with reasons it was rejected)
4. Risks and open questions
5. Rollback plan (what happens if this needs to be reverted)

Write the design document now using only the information provided above.

Make this prompt yours

Engineering

AI Prompt to Triage and Prioritize Engineering Issues Using Linear's MCP Server

This Linear MCP prompt helps engineering leads, team leads, and project managers use an AI assistant connected to Linear's Model Context Pro…

ROLE
You are an engineering triage assistant with access to a Linear workspace through its MCP server integration.

CONTEXT
Team or project: [TEAM_OR_PROJECT_NAME]
Time window: issues updated or opened in the last [TIME_WINDOW]
Priority scale in use: [PRIORITY_SCALE_DEFINITION]
Current sprint or cycle goal: [SPRINT_GOAL]

TASK
1. Pull all open issues matching the team, project, and time window above through the Linear MCP connection.
2. Group the issues into: blocked, in progress, and not started.
3. For each issue, assess severity using this rubric: [SEVERITY_RUBRIC], customer or revenue impact, how long it has been open, and whether it blocks other issues.
4. Flag any issue missing a priority, assignee, or label, and list it separately as a hygiene issue rather than ranking it.
5. Produce a prioritized list of the top [NUMBER] issues the team should work on next, with a one-line justification for each ranking.
6. Note any issues that appear to duplicate each other or contradict the stated sprint goal.

CONSTRAINTS
- Do not invent issue data that is not present in the Linear workspace; if a field is missing, say so explicitly.
- Keep each justification to one sentence.
- Do not take any write actions (status changes, reassignments) unless I explicitly confirm each one.

OUTPUT FORMAT
1. Hygiene issues (missing priority, assignee, or label) - bullet list
2. Blocked issues - bullet list with blocker noted
3. Prioritized list of top [NUMBER] issues - numbered, with one-line justification each
4. Possible duplicates or conflicts with sprint goal - bullet list

Make this prompt yours

Engineering

AI Prompt to Design a Caching Strategy for a High-Traffic API Endpoint

This prompt asks ChatGPT, Claude, or Gemini to design a caching strategy for a high traffic API endpoint , covering where to cache (client,…

ROLE: You are a backend engineer designing a caching strategy for a production API.

CONTEXT:
- Endpoint: [DESCRIBE THE ENDPOINT, e.g. "GET /api/products/:id"]
- Traffic pattern: [READ-HEAVY / WRITE-HEAVY, APPROXIMATE REQUESTS PER SECOND]
- Data shape: [SHARED/PUBLIC DATA OR PER-USER/PER-TENANT DATA]
- Freshness requirement: [HOW STALE CAN THE DATA BE, e.g. "up to 2 minutes" or "must reflect writes immediately"]
- Current infrastructure: [E.G. "Redis available", "CDN in front of API", "no caching layer yet"]

TASK:
1. Recommend where to cache (client, CDN/edge, application-layer, database query cache) and justify the choice based on the context above.
2. Define the cache key structure, including how it avoids collisions across users or tenants if relevant.
3. Specify the TTL and, separately, the invalidation triggers (e.g. invalidate on write, pub/sub cache bust).
4. Call out at least two failure modes specific to this design (e.g. thundering herd, stale-after-write, cache stampede) and how the design mitigates each.
5. List what monitoring or metrics should confirm the cache is working (hit rate, latency improvement).

CONSTRAINTS:
- Do not assume a caching technology I haven't mentioned; ask if it's unclear
- Keep the recommendation specific to the traffic pattern and freshness requirement given, not a generic caching tutorial

OUTPUT FORMAT:
- A short written plan with headed sections: Cache Layer, Cache Key Design, TTL & Invalidation, Failure Modes & Mitigations, Monitoring

REQUEST:
[DESCRIBE YOUR SPECIFIC ENDPOINT AND SITUATION HERE]

Make this prompt yours