// troubleshooting guide

Diagnosing a slow SQL query

One query is slow, every time it runs. The same five steps work on SQL Server, PostgreSQL, MySQL, SQLite and Oracle: measure, get the real plan, find the expensive step, check the estimates, fix the access path.

Covers SQL Server PostgreSQL MySQL SQLite Oracle

The symptom

This is the general method. Each engine has its own commands - the engine guides cover them in detail - but the diagnosis is the same shape everywhere, and skipping a step is how people end up adding indexes that do not help.

Diagnose it

Step 1: measure the query alone

Run it outside the app with timing on, and note three numbers: wall-clock time, rows returned, and how long the engine says it spent on CPU vs waiting. If it is fast standalone, the problem is the app (chatty N+1 queries, connection waits) or blocking - not this SQL.

Step 2: get the real plan, not the estimated one

Four of the five engines can execute the query and show what actually happened: SET STATISTICS IO, TIME plus the actual plan on SQL Server, EXPLAIN (ANALYZE, BUFFERS) 在 PostgreSQL 上, EXPLAIN ANALYZE on MySQL 8.0.18+, and /*+ gather_plan_statistics */ 與 DBMS_XPLAN.DISPLAY_CURSOR(NULL, NULL, 'ALLSTATS LAST') on Oracle. SQLite's EXPLAIN QUERY PLAN only shows the chosen plan without running it; the sqlite3 shell 的 .scanstats on adds actual rows per step where the build supports it.

Step 3: find the most expensive step

Plans are trees; the cost concentrates in one or two nodes. The usual suspects: a table scan on a table with millions of rows, a sort or hash that spills to disk, a nested loop re-executing a lookup thousands of times, or a filter throwing away most of the rows it read.

Step 4: check the estimates on that step

Compare estimated rows with actual rows on the expensive node (per loop: PostgreSQL reports actual rows per loop, Oracle's A-Rows is the total over all starts). If they differ by 10x or more, the optimizer chose the plan from bad information. Refresh the statistics before adding an index, because a new index costed from the same bad estimate may not get used. If fresh statistics do not close the gap, the predicate itself is the problem: correlated columns, a function on the column, or a value the histogram cannot see.

Step 5: fix the access path the step wants

The expensive node tells you the fix: a scan wants an index whose leading columns match the predicate; a sort that spills to disk wants fewer or narrower rows going into it, more sort memory, or an index that already delivers the rows in order; a loop with thousands of probes wants the inner table's join column indexed. Make the change, re-run the plan, and confirm the node changed shape and the time dropped. Paste each plan into the query plan viewer to read the operators and costs, and run messy SQL through the 格式化工具 first so the plan's query matches what you think you wrote.

Fix it

The fix follows from the expensive step, and it is almost always one of four things: an index, statistics, a rewrite, or nothing (the query returns a million rows and the engine is already doing it as cheaply as possible - the fix is returning fewer rows).

When the plan is already indexed and the estimates are honest, look at what the query asks for: SELECT * rows the app never reads, functions applied per row, or predicates in the application that could live in the WHERE clause. A rewrite that lets the engine filter early beats any index on a wide row.

The checklist

Work through it in order. Each step gives you the evidence for the next one.

  1. Run the query standalone with engine timing; confirm it is slow by itself.
  2. Capture the actual (executed) plan, not the estimated one.
  3. Identify the one or two most expensive nodes in the plan tree.
  4. Compare estimated vs actual rows on those nodes; diverge means statistics first.
  5. Add the index the scan asks for: equality columns first, range column last, INCLUDEs for the SELECT.
  6. Re-run the plan and verify the expensive node changed shape.
  7. Record before/after time and logical reads so the change is provable.

Questions that come up

The query is fast in the tool and slow in the app. Why?

Different plans from different sessions (settings that change the plan, like parameter types), blocking from other sessions, or the app issuing the query many more times than you think (N+1). Run the app's exact statement with the app's exact parameters, and check for lock waits while it runs.

Should I just add a hint to force a better plan?

Rarely. A hint pins the plan to today's data shape; when the data changes, the hint keeps forcing yesterday's plan. Add the index or fix the statistics the optimizer is missing first, and treat hints as a last resort you document.

How do I tell CPU cost from I/O cost in a slow query?

Read the engine's counters: CPU time vs elapsed time from SET STATISTICS TIME on SQL Server, the BUFFERS counts on PostgreSQL, rows examined in the slow log or the Handler_read% status counters on MySQL, Buffers and A-Time in DBMS_XPLAN on Oracle. Elapsed far above CPU means the query is waiting (disk, locks, the network). High CPU with few reads means functions, sorts or row-by-row work; high reads means the access path. They lead to different fixes.

When is a slow query not the query's fault?

When the plan is a seek, the estimates match, and the reads are low but it still takes seconds: it is waiting, not working. Check for locks, log flush waits, or a saturated server - see the blocking and high CPU guides for those paths.

Where can I compare two plans?

The free web plan viewer at /tools/query-plan-viewer reads one plan at a time (SQL Server XML, PostgreSQL and MySQL EXPLAIN, SQLite EXPLAIN QUERY PLAN, Oracle DBMS_XPLAN), so open the before and after plans in two browser tabs. The SQLly desktop app keeps the plans captured in each query tab and compares any two of them, listing the operators that regressed, improved, appeared or disappeared.

// fix it where the query lives

Run these queries in SQLly

SQLly is a native SQL workbench for macOS, Windows and Linux. The query plan viewer and formatter these guides link to are built into its editor.