MariaDB ANALYZE for Slow Queries - Compare the Estimate with What Actually Ran
MariaDB ANALYZE for Slow Queries - Compare the Estimate with What Actually Ran
A query can have a plausible execution plan and still feel unexpectedly slow. Standard EXPLAIN helps us see what MariaDB intends to do, but an intention is not an observation. How many rows did each step actually read? How often did a nested step run? Where did this particular execution spend its time?
MariaDB's ANALYZE statement can narrow that gap. It executes an explainable statement and adds observed execution statistics to the plan. That extra evidence is useful, but it comes with an important safety boundary: ANALYZE is not a harmless spelling of EXPLAIN. This article develops a restrained workflow for read-only queries, explains the most useful fields, and keeps one run from becoming an oversized conclusion.
First, keep the safety boundary visible
MariaDB documents EXPLAIN as a way to obtain the optimizer's execution plan for a SELECT, UPDATE, or DELETE. It does not execute the data statement, although it can still acquire metadata locks while inspecting the required table information.
ANALYZE crosses a different boundary: it invokes the optimizer, runs the statement, and returns an annotated plan instead of the normal result set. For a SELECT, MariaDB performs the read and discards the rows that would otherwise be returned. For an UPDATE or DELETE, the changes really happen.
That makes the safest first use deliberately narrow: begin with a SELECT whose cost and locking behavior you understand. Do not paste ANALYZE in front of a write statement merely to see its plan. Use ordinary EXPLAIN for that initial inspection, and test potentially expensive reads on an appropriate replica or staging dataset when production impact is uncertain.
Start with an estimate, then collect an observation
Consider a small CMS query that retrieves recent published posts:
SELECT id, title, slug, created_at
FROM posts
WHERE status = 'published'
AND is_deleted = 0
ORDER BY created_at DESC
LIMIT 20;
The first step is still ordinary EXPLAIN:
EXPLAIN
SELECT id, title, slug, created_at
FROM posts
WHERE status = 'published'
AND is_deleted = 0
ORDER BY created_at DESC
LIMIT 20;
This plan tells us which table access method and key MariaDB expects to use. In tabular output, rows is an estimate of the rows found for each key lookup. The estimate is not a measurement of the completed query, nor is it the number of rows returned to the application.
After checking that the query is safe to run, place ANALYZE before the same SELECT:
ANALYZE
SELECT id, title, slug, created_at
FROM posts
WHERE status = 'published'
AND is_deleted = 0
ORDER BY created_at DESC
LIMIT 20;
The tabular plan now includes observed columns. The most immediate comparison is rows against r_rows, and filtered against r_filtered. The r_ prefix is a useful reminder that these values came from this run rather than only from optimizer estimates.
Read estimates and observations as pairs
According to the ANALYZE reference, r_rows reports how many rows were actually read from a table, while r_filtered reports the observed percentage left after a condition was applied. Their unprefixed counterparts are predictions.
A close estimate is reassuring, but a mismatch is not automatically an error. It is a question worth locating. Perhaps the available statistics do not represent the current data distribution. Perhaps one parameter selects a common value while another selects a rare one. Perhaps a later filter removes most rows only after MariaDB has already read them. The plan identifies where the assumption and this execution diverged; it does not choose the repair for us.
Join plans need another layer of care. MariaDB lists tabular plan rows in join order, and a row estimate can apply per lookup from the preceding step. An inner table that reads only a few rows per lookup may still do substantial work if that lookup repeats thousands of times. This is one reason that a single attractive r_rows value can be misleading when separated from execution count.
An observed value can also be NULL. MariaDB's documentation demonstrates that this may mean a later table was never scanned because an earlier condition produced no matching path to it. In other words, NULL is not necessarily missing instrumentation; it can describe a plan node that did not run.
Use JSON when loops and time matter
Tabular output is compact, but ANALYZE FORMAT=JSON exposes more execution detail:
ANALYZE FORMAT=JSON
SELECT id, title, slug, created_at
FROM posts
WHERE status = 'published'
AND is_deleted = 0
ORDER BY created_at DESC
LIMIT 20;
Two fields are especially useful. r_loops shows how many times a plan node executed. r_total_time_ms shows the total time spent in that node. The timing is inclusive when a node has children, so parent and child times must not be added together as though they were independent costs.
Together, loops and time help distinguish different shapes of work. A node might be individually cheap but repeat many times. Another might run once and dominate the execution. This does not make the largest number guilty by itself, but it gives the investigation a better starting point than the query's total duration alone.
Recent MariaDB versions can also report selected InnoDB engine statistics under r_engine_stats, such as pages accessed or read. Those fields are version-dependent, and zero-valued members can be omitted. Treat them as optional evidence, not as fields that every server or every plan must display. Check SELECT VERSION() and the documentation for the server being examined.
Scope matters here. MariaDB explicitly notes that its JSON plan output differs from MySQL's. A parser, dashboard, or explanation written for one product should not be assumed to understand the other merely because both accept the words EXPLAIN FORMAT=JSON.
ANALYZE is not ANALYZE TABLE
The similar names invite a costly misunderstanding. ANALYZE SELECT ... runs one query and reports what occurred during that execution. ANALYZE TABLE posts is an administrative statement that analyzes and stores key-distribution statistics for the optimizer.
The first is an observation tool. The second changes the statistical information available for future planning and can consume meaningful time and resources on large tables. A gap between rows and r_rows may motivate a closer look at statistics, but it does not prove that immediately running ANALYZE TABLE is the correct response. Data skew, query structure, index design, and parameter choice can produce similar symptoms.
A restrained diagnostic workflow
- Capture the exact query shape. Keep joins, filters, ordering, and limits. Replace sensitive values carefully, while remembering that different parameter values can produce different selectivity.
- Assess execution risk. Confirm that the example is a read-only
SELECT. Consider table size, locks, expected scan work, replica availability, and whether a production run is justified. - Run ordinary
EXPLAIN. Record the chosen access type, key, join order, estimated rows, and filtering. This preserves the optimizer's prediction before execution data is mixed in. - Run
ANALYZEunder controlled conditions. Start with the tabular form. Use JSON when repeated nodes, sorting, or timing require a deeper view. - Find the largest meaningful discrepancy or repeated work. Compare estimate with observation, then read that node in the context of its parent, children, and loop count.
- Form one hypothesis. The candidate change might involve the query shape, an index, stale or insufficient statistics, or simply a value distribution that the generic plan cannot represent well.
- Change one thing and repeat comparably. Use representative data and parameters. Keep the server conditions as similar as reasonably possible, and verify application behavior as well as the plan.
This process is intentionally slower than seeing ALL or a high row count and immediately adding an index. A full scan can be reasonable for a small table or a query that needs much of it. Conversely, an index name in the plan does not prove that the query performs little work. The relationship between estimated rows, observed rows, loops, filtering, and elapsed time is more informative than any one label.
What one execution cannot establish
ANALYZE reports what happened once, with particular data, parameters, cache state, server load, and concurrent activity. A warm buffer pool can make the same access pattern look very different from a cold read. A frequent status value can exercise a different amount of work from a rare one. Another request competing for CPU or storage can alter timing without changing the plan.
For those reasons, r_total_time_ms is evidence, not a portable benchmark. Repeat observations where the cost is acceptable, retain representative parameter cases, and pair database evidence with application-level latency. A faster isolated query may not improve the page if network calls, template rendering, or lock waits elsewhere dominate the request.
The tool also cannot decide whether operational complexity is worth a small gain. An extra index consumes storage and adds write work. Persistent statistics require collection and maintenance. A rewritten query may be harder to understand. Those are engineering tradeoffs, not values hidden in a JSON field.
Let the observation refine the question
MariaDB ANALYZE is most useful between suspicion and intervention. EXPLAIN says what the optimizer expects; ANALYZE adds what one execution observed. Comparing the two can reveal a mistaken row estimate, a heavily repeated lookup, or a node where time accumulates.
That evidence narrows the next question, but it is not a verdict. Keep write statements outside casual analysis, distinguish execution analysis from ANALYZE TABLE, and compare runs under conditions that make the comparison meaningful. The goal is not to make every estimate perfect. It is to replace an untested guess about a slow query with a smaller, safer hypothesis.
