ReinDBby Bandlei

6. The statement tuning procedure

Brett Rosenblatt · Database tuning guide v1.3 · PDF

Once the evidence points at specific statements, tune them with a fixed procedure. The procedure matters more than any single trick: it keeps you from fixing symptoms, and it leaves a record that the next person can follow.

6.1Ten steps

  1. Pick the target and state the goal. For example: "Statement 7f3k...: 2.1 s average between 09:00 and 11:00, 40,000 calls per hour. Goal: under 200 ms."
  2. Record its baseline. Executions, average and worst time, logical reads per execution, rows per execution, the plan identifier, and the split between CPU and waits. Logical reads per execution is the most stable efficiency measure you have: it doesn't depend on cache state or concurrency.
  3. Get the full text and real parameter values. Statement statistics normalize literals away, and plans depend on values, so find the values the slow executions actually used (see the engine note after these steps).
  4. Capture the actual plan with runtime row counts, not just the estimated plan (section 6.2).
  5. Read the plan (section 6.3). Find where estimated and actual rows diverge, where the time and buffers accumulate, and which access paths and join methods were chosen.
  6. Form one hypothesis you can state in a sentence: "The optimizer expects 12 rows from orders but gets 480,000, because status is skewed and has no histogram, so it chose nested loops."
  7. Choose the least invasive fix that addresses the cause, in roughly this order: rewrite the query (if you own the code); fix statistics; add or change an index; pin a plan as a temporary measure; change a setting; change the schema.
  8. Test with production-like data and several representative parameter values, especially values from both ends of a skewed distribution. Compare logical reads and rows, not just elapsed time.
  9. Deploy with a rollback script, at a quiet hour, and tell the people who own the application.
  10. Verify against the baseline at the same hour on the following days, and record what changed, why, and the before and after numbers.

6.2Getting the actual plan

An estimated plan shows what the optimizer intends. An actual plan shows what happened: the rows each step produced, how many times it ran, and where the time and buffers went. Capture the actual plan whenever you can, either by running the statement once with runtime statistics or from the engine's record of recent executions. Running a statement to get its actual plan really executes it, so for data changes use a copy of the data, or a transaction you roll back.

6.3Reading the plan

Read a plan from the inside out, but start with the numbers: where do estimated and actual rows part ways, and where does the time go?

What you seeWhat it usually meansTypical fix
Estimated rows far from actual (10× or more)A bad cardinality estimate, and every decision after it is built on sandStatistics, histograms, extended statistics, predicate rewrites (section 6.4)
Full scan of a large table that returns few rowsA missing or unusable indexAdd an index, or make the predicate sargable (Chapter 7)
Nested loops with a large outer row countAn underestimate, or no index on the inner join columnFix the estimate; index the inner join column; let the optimizer choose a hash join
Sort or hash spilling to temp or diskToo many rows reaching the operation, or too little memory for itFilter earlier; support the order with an index; raise memory for that session
Many lookups back to the table, one for each index entryThe index finds rows but doesn't cover the queryA covering index, or accept a scan when many rows qualify
A conversion function or cast wrapped around a columnA data type mismatch that disables an indexMatch parameter and column types
A filter applied late, after many rows were readA predicate the access path can't useRewrite the predicate; index the filtered column
One step executed thousands of times (high Starts or loops)A correlated subquery or a function called per rowRewrite as a join or a set-based aggregate
A parallel plan for a short OLTP queryA parallelism threshold that is too low, or an overestimateStatistics; parallelism settings (Chapter 11)

6.4Cardinality: the root of most bad plans

The optimizer chooses join order, join method and access path from its row estimates. When the estimates are wrong, good plans happen only by luck.

CauseRemedy
Stale statisticsFix the maintenance job; gather statistics after big loads and purges
Skewed column without a histogramBuild a histogram on the column, or a finer one
Correlated columns (city and postal code, status and region)Statistics on the column combination
Expressions on columnsStatistics on the expression, or an index on it
Values beyond the histogram (ascending keys such as today's date)Gather statistics more often on fast-growing tables
Parameter sensitivity (one plan can't serve all values)Let the engine keep several plans, recompile infrequent calls, or split very different cases into separate code paths (Chapter 9)
Table variables and functions that return tables, with fixed row guessesTemporary tables, which have statistics

After a major upgrade, check whether the engine kept the optimizer statistics, and if it didn't, gather them before users arrive. On every engine, gather statistics after bulk loads and large purges rather than waiting for the automatic job.

6.5Plan stability tools: a stopgap, not a cure

Sometimes you need a good plan today and the real fix takes a release cycle. Every engine offers a way to pin or steer a plan. Use it, write down why, and come back to it.

EngineTools
PostgreSQLNo built-in plan forcing. Fix the root cause with statistics and indexes; plan_cache_mode (12+) for generic or custom plans of prepared statements; the third-party pg_hint_plan extension where hints are unavoidable
MySQLOptimizer hints (/*+ ... */), index hints (USE INDEX, FORCE INDEX, IGNORE INDEX), optimizer_switch; histograms to correct estimates
SQL ServerQuery Store plan forcing (2016+); Query Store hints (2022); automatic plan correction (2017+, Enterprise Edition); USE HINT, OPTIMIZE FOR and OPTION (RECOMPILE); plan guides
OracleSQL plan baselines (SQL Plan Management, part of Enterprise Edition without a pack; Standard Edition 2 has restrictions); hints; adaptive cursor sharing. SQL profiles and the SQL Tuning Advisor need the Tuning Pack

This is one chapter of the free database tuning guide for PostgreSQL, MySQL, SQL Server and Oracle. Download the whole guide as a PDF.