Example result: Speed up a slow SQL query
AI-generated example · SQL Optimiser
Updated

Speed up a slow SQL query

This prompt helps you optimise a slow query. You paste the query with the database, table sizes and existing indexes, and it explains why it is slow and suggests indexes and a rewrite. Test on a copy first.

text-sql-optimise — chatgpt — 54 words

Help me optimise this slow SQL query.

Database: [POSTGRES / MYSQL / SQL SERVER]
Query: [PASTE]
Table sizes: [ROW COUNTS]
Existing indexes: [LIST]

Explain why it is slow, suggest indexes and a rewritten query, and tell me what to look for in EXPLAIN output. Warn me about any change that could alter the results.

Paste the EXPLAIN ANALYZE output if you can. It removes the guesswork.

Get a better result

What you will get

An explanation of why the query is slow, suggested indexes, a rewritten query, what to look for in the EXPLAIN output and a warning about any change that could alter the results.

Why it works

Query tuning depends on facts the AI cannot see, so the prompt asks for the database engine, table sizes and existing indexes up front. Asking for an explanation first, then indexes, then a rewrite, keeps the reasoning visible so you can check it. The warning about changed results matters most: a fast query that returns the wrong rows is worse than a slow one.

Common mistake

The rewrite returns different rows.

Fix: Run both queries on a copy of the data and compare the counts. Swapping a LEFT JOIN or an OR for something faster can silently drop rows, which is why the prompt asks for warnings.

Also watch for
  • It suggests an index on every column. Give the write volume of the table. Indexes speed reads but slow inserts, and a busy table cannot carry many.
  • The advice is generic because it is guessing. Paste the EXPLAIN ANALYZE output, as the tip says. The real plan shows which step is slow.
Try a variation: check an ORM query

Paste the SQL your ORM generates from the logs and ask what to change in the ORM code, not the raw SQL, to get the faster query.

Still not right? Reply with this

Here is the EXPLAIN ANALYZE output for the original query: [PASTE]. Point to the slowest step and tell me which one of your suggestions fixes it.

More chat & writing prompts

See all 465 →