0
Diagnose and rewrite a slow SQL query with execution-plan reasoning
This query is too slow. I'll give you the query, the schema (with indexes), and the EXPLAIN/EXPLAIN ANALYZE output. Do this:
1. Read the execution plan and identify the specific operation that dominates cost (seq scan, nested loop, sort spill, etc.), quoting the relevant line from the plan.
2. Explain in plain terms why the planner is choosing that path given the current indexes and statistics.
3. Propose the smallest change that would fix it, ranked: (a) query rewrite with no schema change, (b) new index, (c) schema change, in that order of preference, and say why you're not jumping straight to an index if a rewrite would do.
4. Show the rewritten query or CREATE INDEX statement.
5. Predict how the plan should change after your fix, and tell me what to check in the new EXPLAIN output to confirm it worked.
6. Flag if the fix could hurt a different query that shares the same table (e.g. a new index that slows down writes on a hot table).
Database: {{database, e.g. Postgres 15}}
Query: query
Schema/indexes: schema
EXPLAIN output: explain_output