DEV Community

Dakota Huang
Dakota Huang

Posted on

Pin the Query Plan First: Characterization Tests for a Messy SQL Refactor

You cannot safely refactor a query whose access path you have not characterized. In a messy repository, the useful unit of change is one query with a pinned plan and a pinned result set. Capture both before editing; then make the smallest change that keeps both explainable.

EXPLAIN QUERY PLAN is a SQLite feature. The official documentation describes its output in terms of SCAN and SEARCH records for table access and USE TEMP B-TREE records when SQLite needs a temporary B-tree for ORDER BY, GROUP BY, or DISTINCT: https://www.sqlite.org/eqp.html. That makes the plan a useful performance-contract snapshot. It is not a correctness oracle; a plan can stay identical while rows change, so keep a row snapshot too.

Who this is for

You are touching a query layer assembled from strings, helpers, or an ORM escape hatch. Rows come back, tests are green, and you do not know whether your rewrite just turned an index seek into a full scan.

Row-level golden tests will not show you the plan. Identical rows can hide a plan that now sorts in a temporary B-tree. Plan pinning will not show you wrong data either. A plan-identical change can still return the wrong rows.

Why the plan is the right seam

The documentation's SCAN and SEARCH distinction and its temporary B-tree detail are the parts to watch. A plan snapshot records the access path and sort strategy for specific SQL, schema, statistics, and parameters. It is a characterization test, not proof of optimality. Re-baseline deliberately when the fixture or SQLite environment changes; review the plan diff like code.

Prerequisites

  • A SQLite build you can run locally, plus its version string.
  • A deterministic fixture database, small enough to rebuild routinely.
  • A list of the query shapes you actually care about, not every query in the repository.
  • Representative parameter values for each query shape.

Pin the top handful by call frequency. Pinning everything produces noise and a snapshot nobody reads.

Step 1 — Build a deterministic fixture

Use deterministic data. No random seeds, no production dumps, no clock-dependent values. A fixture might have customers and orders, with an index on orders(customer_id, status). Generate rows from a formula so two runs produce the same logical rows. Keep the fixture beside the snapshots. A snapshot without its fixture is unreproducible.

Step 2 — Freeze the environment into the snapshot

Record the SQLite version string and whether statistics were collected. The SQLite documentation notes that running ANALYZE can cause SQLite to choose different query plans and that there is no proof it will always be beneficial; it can make some subsequent queries slower: https://www.sqlite.org/lang_analyze.html. Decide whether the fixture includes statistics and stay consistent. If statistics are present, the snapshot should say so.

Step 3 — Run the observation test

Inputs: a fixture database, a list of query names with SQL text and representative parameter values, a baseline plan record set, and a baseline row set.

Observe: for each query, collect the EXPLAIN QUERY PLAN detail records and execute the query to collect rows. Sort rows deterministically, or include an ORDER BY in the query. Compare both against the baseline. Store plan and rows as two artifacts even if they live in one versioned file; the file layout must not hide which one failed.

Interpret a mismatch: a plan mismatch means the access path, join order, or temporary B-tree use changed. A row mismatch means the result changed. If the plan matches but rows differ, treat it as a correctness regression. If rows match but the plan differs, treat it as a performance regression for those inputs. If both match, you have no evidence of change for those inputs; you do not have proof for unobserved parameters. A check run should fail non-zero on either mismatch and show the query name with before and after values.

Step 4 — Make the smallest safe change

One query per commit. If the plan changes, revert or justify the change in the commit message. Keep the snapshot in the same commit as the SQL so reviewers see the plan diff beside the code diff.

Step 5 — Read the plan diff, not the SQL diff

A rewrite that still reports SEARCH ... USING INDEX is boring, and boring is the goal. A rewrite that introduces SCAN or USE TEMP B-TREE FOR ORDER BY is the signal you were looking for.

Snapshot Catches Misses
Plan index loss, added sorts, join order changes wrong results
Rows wrong results, changed filtering cost regressions

Run both. Neither is sufficient alone.

Verify the harness actually fails

Do not trust a green snapshot you have never seen go red. In a scratch copy of the fixture, change the schema or predicate so the plan should change (for example, remove the index or add a selective filter that defeats it). Repeat the observation. Expect a reported plan mismatch and a failing exit status. If the check stays green, the snapshot is not reading what you think it is. This verifies detection for that deliberate change, not correctness of the query.

Failure modes

Environment drift. If the SQLite build changes, re-baseline deliberately and read the diff.

Statistics drift. Running ANALYZE can move plans with no code change. Pin the fixture build step.

Parameter-sensitive plans. If plans vary with parameter values, one value may not exercise the branch you care about. Pin two or three representative values per query.

Retries on write paths. If the harness retries a failed write, check the semantics first. RFC 9110 §9.2.2 says automatic retry of a non-idempotent request is allowed only when you know replay is safe or the original was never applied: https://www.rfc-editor.org/rfc/rfc9110.html#section-9.2.2.

Snapshot as correctness proof. It is not. A plan-identical change can still be wrong, which is why the row artifact exists.

When not to use this

Skip plan pinning when the schema or index change is the point of the work. Skip it when the planner is unstable across runs for reasons you cannot control. Skip it for ORM-generated SQL you cannot shape.

If you already have a representative benchmark you trust, use that instead; a plan snapshot is a cheap substitute for measurement, not a replacement for it.

What to take away

Pin the plan before you touch the query. Change one query per commit. Keep the row snapshot beside it. Verify the harness fails before you trust it passing.


AI assistance disclosure: this article was produced with AI assistance. No code was executed and no benchmark or production result is claimed. A human should verify SQLite behavior for their version and DEV's current publishing policy before posting.

Top comments (0)