How to Optimize a Slow SQL Query with AI (Step by Step)
Paste the query and its execution plan into AI, get ranked fixes, then test each one. A step-by-step method, a copyable prompt, and a worked example.
For Data & Analytics

How do you optimize a slow SQL query with AI?
Give the AI three things: the query, its execution plan (the output of EXPLAIN or your tool's equivalent), and the table definitions with indexes and rough row counts. Ask it to name the slowest step in the plan and propose ranked fixes. Then test every suggestion yourself, on a copy of the data if you can, and compare the plan and run time before and after. AI is good at reading plans and spotting patterns. It cannot see your data, so it can only guess until you measure.
TL;DR
- Never paste a query alone. Without the execution plan, AI is guessing. The plan shows where the time goes.
- Most slow queries have one of a handful of causes: a function wrapped around an indexed column, a missing index,
SELECT *, a join that multiplies rows, or deepOFFSETpagination. - Ask for ranked fixes with reasons, not a rewritten query. You want to understand the change before it touches a dashboard or pipeline.
- Check that the rewrite returns the same rows. A faster query that returns different results is a bug.
- Test index suggestions before creating them. Indexes speed up reads and slow down writes, and the AI does not know your write load.
- Strip real customer data and secrets from anything you paste into a public AI tool, and follow your company's AI policy.
What do you need before you ask AI for help?
Gather four things. Ten minutes here saves an hour of back and forth.
- The exact query, as it runs. If it is generated by a BI tool, copy the SQL from the tool's query log, not the dashboard's visual definition.
- The execution plan with real timings. In PostgreSQL, run
EXPLAIN (ANALYZE, BUFFERS) your_query;. In MySQL 8,EXPLAIN ANALYZE your_query;. In SQL Server, use the actual execution plan in Management Studio. In Snowflake, BigQuery, and Redshift, use the query profile or execution details screen and copy the step list. - The schema:
CREATE TABLEstatements for the tables involved, plus existing indexes (or partitioning and clustering keys in a warehouse). - Context: roughly how many rows are in each table, how often the query runs, and what "fast enough" means. A report that runs once a night has a different target than a dashboard filter that runs on every click.
A word of caution on EXPLAIN ANALYZE: it actually executes the query. That is fine for a SELECT. For an UPDATE or DELETE, wrap it in a transaction you roll back, or ask a database admin.
How do you read an execution plan without being a DBA?
You do not need to master it. You need to find the expensive part. A plan is a tree of steps, and each step reports a cost or a time and a row count. Look for these:
- Full table scans (called "Seq Scan" in PostgreSQL, "Table Scan" or "type: ALL" elsewhere) on large tables, especially when your query filters down to a small number of rows.
- Row estimates far from actual rows. If the plan expected 100 rows and got 2 million, the database chose its strategy on bad information. Stale statistics are often the cause.
- Big sorts or sorts that spill to disk, usually from
ORDER BY,DISTINCT, orGROUP BYon a lot of rows. - Nested loops over large row counts, which means the database repeats an inner lookup millions of times.
- A step that dominates the total time. Fix that one first. Everything else is noise until it is gone.
In a cloud data warehouse the same idea applies, with different symptoms: look for the amount of data scanned, whether partitions or clusters were pruned, and steps that shuffle huge volumes of data between workers.
AI is useful here because it reads plans quickly and explains them in plain words. Ask it to point to the slowest node and explain why it is slow, then check that claim against the timings yourself.
How do you optimize a slow SQL query with AI, step by step?
Step 1: Measure the baseline
Run the query three times and note the run time and the plan. The first run may be slow because data is not cached, so the later runs are a fairer comparison. Write the numbers down. You will compare against them at the end.
Step 2: Remove anything sensitive
Replace real customer names, emails, and account numbers in the query with placeholders. Table and column names are usually fine to share, but check your policy. If your company has an approved internal AI tool, use that one for anything non-trivial.
Step 3: Paste this prompt
Copy this block, fill in the brackets, and paste your material under each heading.
You are a senior database performance engineer. I have a slow SQL query.
Database and version: [PostgreSQL 15 / MySQL 8 / SQL Server / Snowflake / BigQuery / other]
Goal: [e.g., under 2 seconds; it runs on every dashboard filter change]
Approximate table sizes: [orders ~50M rows, customers ~2M rows]
QUERY:
[paste query]
EXECUTION PLAN (with actual timings):
[paste plan]
SCHEMA AND EXISTING INDEXES:
[paste CREATE TABLE and CREATE INDEX statements]
Please do the following:
1. Identify the slowest step in the plan and explain in plain language why it is slow.
2. List up to five fixes, ranked by expected impact. For each: what to change, why it helps, and any risk or trade-off (for example, write overhead from a new index).
3. Give the rewritten query and any index statements for your top fix only.
4. Tell me how to confirm the rewritten query returns exactly the same rows as the original.
5. List what you could not determine because you cannot see my data, and what I should check.
Do not invent table or column names that are not in the schema above.
The last line matters. Models sometimes produce tidy-looking SQL that references columns that do not exist.
Step 4: Read the answer critically
Check each suggestion against the plan you pasted. A good answer points to a specific node ("the sequential scan on orders removes most rows after reading them") and ties the fix to it. A weak answer gives generic advice like "add indexes on all columns in the WHERE clause." Push back with a follow-up: "Which node in the plan does that change affect?"
Step 5: Prove the results match
Before you compare speed, compare output. Two common approaches:
-- Rows in the original but not the rewrite (should return nothing)
SELECT * FROM (original_query) a
EXCEPT
SELECT * FROM (rewritten_query) b;
-- And the reverse
SELECT * FROM (rewritten_query) b
EXCEPT
SELECT * FROM (original_query) a;
(Oracle uses MINUS.) Also compare row counts and a few totals. If the numbers differ, the rewrite changed the meaning, and you should not ship it.
Step 6: Apply one change at a time and re-measure
Make the top fix, rerun the plan, and compare to your baseline. If it helped, stop or move to the next bottleneck. If it did not, paste the new plan back into the same conversation and say "I applied fix 1. Here is the new plan. What is slowest now?" Tuning is a loop, and the AI works best when it sees fresh evidence each round.
Step 7: Test indexes away from production
Create a suggested index on a staging copy first. Check that the plan actually uses it, and ask someone who owns the database before adding it to a busy production table. Every index costs storage and slows inserts and updates.
What does a worked example look like?
Here is a typical dashboard query on PostgreSQL. It returns EMEA orders from one day.
SELECT *
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE DATE(o.created_at) = '2025-03-01'
AND c.region = 'EMEA'
ORDER BY o.created_at DESC;
The plan shows a sequential scan on orders, reading every row and then discarding nearly all of them. A good AI answer will point out two things:
DATE(o.created_at)wraps the column in a function. The database cannot use a normal index oncreated_at, because it would have to computeDATE()for every row first.SELECT *pulls every column from both tables, which moves far more data than the dashboard displays.
The suggested rewrite:
SELECT o.id, o.created_at, o.total, c.name
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.created_at >= '2025-03-01'
AND o.created_at < '2025-03-02'
AND c.region = 'EMEA'
ORDER BY o.created_at DESC;
plus an index to support the date range:
CREATE INDEX idx_orders_created_at ON orders (created_at);
The range condition says the same thing as the DATE() comparison but lets the database jump straight to one day of data. After the change, you would expect the plan to show an index scan on orders instead of a full scan. Then run the EXCEPT check from Step 5 to confirm the same orders come back, and compare run times against your baseline.
Notice what the AI could not know: whether created_at has a timezone issue that makes "one day" mean something different, and whether the table is written to so heavily that another index hurts. Those are your calls.
What are the most common causes of slow SQL queries?
Use this table as a checklist, and as a way to judge whether the AI's diagnosis is reasonable.
| Symptom in the query or plan | Likely cause | Typical fix |
|---|---|---|
| Full scan despite a filter on an indexed column | Function or calculation on the column (DATE(col), LOWER(col), col + 1) | Rewrite as a range or compare against the raw column; or create an expression index |
| Full scan on a large table, no usable index | Missing index on the filter or join column | Add an index matching the filter and join columns |
LIKE '%text' is slow | Leading wildcard defeats a normal index | Use full-text search or a trigram-style index where your database supports it |
| Huge result, slow transfer | SELECT * | Select only the columns you need |
Row counts explode after a join, then DISTINCT | Join on a non-unique key creating duplicates | Fix the join condition; aggregate before joining |
| Subquery runs once per row | Correlated subquery | Rewrite as a join or a pre-aggregated subquery |
| Gets slower on later pages | Deep OFFSET pagination | Keyset pagination (filter on the last seen value) |
| Joins on columns of different types | Implicit type conversion | Align the types or cast the parameter, not the column |
OR across different columns | Planner cannot use one index | Split into UNION ALL branches, if results stay correct |
| Plan estimates wildly wrong | Stale table statistics | Refresh statistics (ANALYZE in PostgreSQL, UPDATE STATISTICS in SQL Server) |
| Warehouse scans far more data than needed | No partition or cluster filter | Filter on the partition column directly; consider clustering |
If the AI's top suggestion is nowhere on this list, it may still be right, but ask it to justify the change from the plan.
Where should you not trust AI on SQL tuning?
- Index advice without workload knowledge. AI cannot see how often the table is written to, how many indexes already exist, or what other queries depend on them.
- Claims about speed. "This will be 10x faster" is a guess. Only your before and after measurements count.
- Database-specific syntax. Hints, index types, and statistics commands differ between systems and versions. Tell the AI your exact database, and verify unfamiliar syntax in the official documentation.
- Semantics. Rewrites that change
LEFT JOINtoINNER JOIN, removeDISTINCT, or move filters betweenONandWHEREcan change results. This is why Step 5 exists. - Invented objects. Check every table, column, and index name in the output against your schema.
- Production changes. Do not run
CREATE INDEX,VACUUM, or schema changes on a live system because a chatbot suggested it. Use your change process.
What if the query is fine but still slow?
Sometimes the SQL is reasonable and the problem sits elsewhere. Ask yourself:
- Is the query asking for too much? A dashboard that aggregates two years of raw rows on every load may need a summary table or a materialized view refreshed on a schedule.
- Is it competing with other work? Locks, a heavy nightly job, or a small database instance can make a good query slow only at certain times.
- Is the BI tool adding the cost? Some tools run many queries per page or fetch far more rows than they display. Check the tool's query log.
- Does the data model fit the question? If every report needs the same five-table join, a pre-joined reporting table may be the right fix, and that is a conversation with your data engineering team.
AI can help you think these through. Describe the use case and ask for options with trade-offs, then take the shortlist to the person who owns the database.
Can you build a tool to track slow queries instead of chasing them one by one?
Query tuning tends to get tracked in chat threads and scattered spreadsheets: which query, who owns it, what the plan showed, what changed, how long it took before and after. A small internal app handles that better. With Remy, you can describe a slow-query tracker in plain English (a form to log a query and paste its plan, an owner and status field, before and after timings, a notes history) and it builds and deploys a full-stack app with a database and sign-in. Your team then has one place to see what has been fixed and what keeps coming back, and you own the app rather than renting another subscription.
Frequently Asked Questions
Can ChatGPT or another AI optimize my SQL query?
Yes, as a reviewer and explainer. It can read an execution plan, spot common problems, and draft a rewrite. It cannot run your query or see your data, so treat every suggestion as a hypothesis to test. The quality of the answer depends heavily on whether you include the plan, the schema, and the table sizes.
Is it safe to paste my company's SQL into an AI tool?
It depends on your company's policy and the tool. Queries can reveal table names, business logic, and sometimes literal values like customer IDs. Remove real data and secrets, and use your company's approved AI tool where one exists. If you are unsure, ask your security or data governance team before pasting anything.
What is the first thing to check when a SQL query is slow?
Get the execution plan and look for the step that takes the most time, usually a full table scan, a large sort, or a join producing far more rows than expected. Then check whether the query wraps indexed columns in functions or selects columns it does not need. These two issues account for a large share of everyday slow queries.
Will adding an index always make my query faster?
No. An index helps only if the database chooses to use it, and the query has to be written so it can. Indexes also take storage and slow down inserts and updates. Test on a copy of the data, confirm in the plan that the index is used, and check with the database owner before adding one in production.
How do I know the optimized query returns the same results?
Run the original and rewritten queries and compare them with EXCEPT in both directions (or MINUS in Oracle). Both should return no rows. Also compare row counts and a few key totals. Do this before you look at speed, because a fast wrong answer is worse than a slow right one.
Useful for
How we source, write, and correct our articles. Editorial standards
Related articles

Data Dictionary Template + an AI Prompt to Fill It In

Data Quality Checks: A Checklist and How to Automate Them

Marketing Attribution Models Explained (With an AI Prompt)
