Audit advanced Works with: Any AI

Database Query and Index Review

Decision tree Has example

Optimize slow queries with evidence.

The Open buttons send the prompt text as currently shown below to that site only when you click. Fill in the placeholders first.

Rate this prompt

Loading ratings…

Help me speed up a slow database query using a decision tree, and do not suggest an index before checking the earlier nodes. Database and version: [DATABASE_AND_VERSION]. The query: [PASTE_QUERY]. Table definitions and existing indexes: [PASTE_SCHEMA]. Execution plan output, if I have it: [PASTE_EXPLAIN_OUTPUT]. Row counts and how slow it is: [SIZE_AND_TIMING].

NODE 1: Is the query returning more rows or columns than the application uses? If yes, rewrite it to fetch less.
NODE 2: Does the plan show a full table scan on a large table? If yes, check whether the filter or join columns have a usable index, and whether a function or cast on the column prevents its use.
NODE 3: Are joins producing more rows than expected (missing join condition, one-to-many fan out)? Show the fix.
NODE 4: Is sorting or grouping the cost? Check for an index that matches the order.
NODE 5: Is it called many times (the N+1 pattern)? Suggest batching.
NODE 6: Is the statistics or table design the problem?

For each node say "applies" or "does not apply" with evidence. Then give the rewritten query, the exact index definition with its write cost, and how to compare the plans before and after. Do not run anything on production first.

Fill in before use

Optional: type your details and the prompt above updates. Nothing is saved or sent.

Replace each bracketed placeholder with your own details, then paste into Any AI or another assistant.

See an example result (fictional data)
NODE 1: Query returns 40 columns but the page uses 5. Rewrite to select needed columns.
NODE 2: Plan shows Seq Scan on orders (2.1 million rows) because WHERE lower(email) = ... blocks the index on email. Fix: store emails lowercase or add an index on lower(email).
NODE 5: N+1 pattern: 50 queries per page load. Fix: one query with IN.
Rewritten query: SELECT id, status, total FROM orders WHERE customer_id = $1 AND created_at >= $2 ORDER BY created_at DESC LIMIT 50;
Index: CREATE INDEX idx_orders_customer_created ON orders (customer_id, created_at DESC); adds a small cost to each insert.
Compare: run EXPLAIN ANALYZE before and after; expect the scan to become an index scan.

Illustrative only, made-up data. Your results will differ and must be reviewed.

Related prompts