EXPLAIN

EXPLAIN renders a logical plan as PostgreSQL-style text or JSON. The output looks like PostgreSQL's, but it describes the plan as parsed, before the optimizer and the engine's rewrites, and its costs are placeholders. Scan lines do reflect the access path the executor would pick, and row counts for unfiltered scans are real (source: src/query/engine.rs, execute_explain; src/plan/explain.rs).

Syntax

parse_explain accepts (source: src/query/sql/parser.rs, parse_explain; see parser):

Form Result
EXPLAIN stmt text plan
EXPLAIN ANALYZE stmt text plan, executes stmt
EXPLAIN (FORMAT JSON) stmt JSON plan
EXPLAIN (ANALYZE [TRUE \| FALSE], ...) stmt sets analyze
EXPLAIN (BUFFERS, COSTS, VERBOSE, TIMING ...) stmt options are skipped

Any format other than JSON gives text. EXPLAIN VERBOSE stmt without parentheses is not accepted, because VERBOSE is then read as the start of the statement (source: src/query/sql/parser.rs, parse_explain).

The result is LogicalPlan::Explain { plan, analyze, format } (source: src/plan/logical.rs, LogicalPlan::Explain).

What plan is shown

execute_plan_inner sends Explain to execute_explain. The inner plan has not been through:

  • resolve_natural_joins and promote_where_equijoins, which do not descend into Explain;
  • the optimizer, whose apply_rule does not descend into Explain;
  • row-level security, view expansion, subquery resolution and pushdown_filters_into_scans, which execute_plan_inner applies only when the top node is a query node.

(source: src/query/engine.rs, execute_plan_inner, resolve_natural_joins, promote_where_equijoins; src/plan/optimizer.rs, apply_rule)

So a comma join is shown as a cross join with a filter on top, a view is shown as a scan of the view's name, and RLS predicates do not appear. Privilege checks do apply: EXPLAIN SELECT v FROM priv_secret is refused for a user without SELECT on the table. Tested by table_privileges_cover_subqueries_ctes_views_and_set_ops in src/query/engine.rs.

Not verified: the shapes for comma joins and views follow from the code but no test asserts them.

Before rendering, explain_inline_filters moves a Filter that sits directly on a bare Scan into the scan (through Project, Sort, Limit, Distinct, Alias and LockRows), so the scan line can show its access path (source: src/query/engine.rs, explain_inline_filters).

Text format

The result has one text column, QUERY PLAN, with one row per line. Child nodes are indented with -> per level (source: src/query/engine.rs, execute_explain; src/plan/explain.rs, explain_plan_text_ctx).

Plan node Line
Scan, sequential Seq Scan on t [alias], then Filter: (...) if filtered
Scan, index path Index Scan using <index> on t, then Index Cond: (...)
Filter child, then a Filter: line
Project folded into its child (no line)
Join Inner / Left / Right / Full Hash Join, Hash Left Join, Hash Right Join, Hash Full Join, with Hash Cond:
Join Cross Nested Loop
Join Semi / Anti Hash Semi Join, Hash Anti Join
LateralJoin Nested Loop or Nested Loop Left Join, with Join Filter:
Aggregate Aggregate or HashAggregate with Group Key:
Sort Sort with Sort Key:
Limit Limit with (limit=N offset=M)
Distinct Unique
LockRows LockRows (strength)
Alias Subquery Scan on a
RecursiveCTE Recursive Union (CTE: name)
Union Append for UNION ALL, else HashSetOp Union
Intersect, Except HashSetOp Intersect, HashSetOp Except
TableFunction Function Scan on f(args)
Values Values Scan (n rows)
Insert, Update, Delete Insert on t, Update on t, Delete on t
Empty and anything not listed Result

(source: src/plan/explain.rs, explain_plan_text_ctx)

Join labels are fixed by join type. They do not reflect whether the executor will use its hash join or nested loop (see executor): a Right or Full join, or an inner join on a non-equality condition, is labelled Hash ... Join but runs as a nested loop.

Expressions are printed by expr_to_text; LIKE is printed as ~~, as PostgreSQL does (source: src/plan/explain.rs, expr_to_text).

Tested by test_explain_text_seq_scan, test_explain_text_filter, test_explain_text_project_folds, test_explain_ctx_index_scan, test_explain_ctx_seq_scan_real_cardinality and test_explain_no_ctx_unchanged in src/plan/explain.rs.

Access path on scan lines

EngineExplainStats::scan_access mirrors the start of the executor's access-path cascade (source: src/query/engine.rs, explain_scan_access, EngineExplainStats; compare access paths):

Filter matches Shown as Rows
no filter Seq Scan real key count of the table (explain_table_rows)
primary-key equality Index Scan using <t>_pkey 1
primary key IN (...) Index Scan using <t>_pkey number of list items
single-column UNIQUE Index Scan using <t>_key 0 or 1
secondary index candidates Index Scan using <catalog index name> (or <t>_idx) number of candidate keys
anything else Seq Scan round(total × 0.33), at least 1

The composite-unique, secondary-range, GIN, full-text, HNSW, primary-key integer-range and primary-key prefix paths are not mirrored, so a query served by one of them is shown as Seq Scan. explain_table_rows counts keys by scanning the table's key prefix, so EXPLAIN on an unfiltered large table costs a full key scan (source: src/query/engine.rs, explain_table_rows).

Tested by test_mysql_varchar_pk_case_insensitive_point_lookups in src/query/engine.rs (expects Index Scan for primary-key equality and IN lists) and sort_key_index_serves_point_lookups in src/protocol/clickhouse/mergetree.rs.

Row and cost numbers

Every node line carries (cost=0.00..R.00 rows=R width=8), where R is the estimated row count. Costs are not computed; the header comment of src/plan/explain.rs calls them placeholders, and the cost model is not consulted (see cost model and statistics) (source: src/plan/explain.rs, cost_str_rows, STARTUP_COST, PLAN_WIDTH).

Node Estimated rows
Scan from the access-path table above
Filter input × 0.33 (DEFAULT_FILTER_SELECTIVITY)
Limit min(limit, input)
Aggregate 1 without GROUP BY, else the input count
Join Cross: left × right; Semi/Anti: left; others: max(left, right)
Union sum; Intersect: min; Except: left
Values number of rows

(source: src/plan/explain.rs, est_rows)

ANALYZE statistics are not used for these numbers.

JSON format

FORMAT JSON returns one row holding pretty-printed JSON (crate serde_json) of the form [{"Plan": {...}}]. Each node has Node Type, and where relevant Relation Name, Alias, Index Name, Startup Cost, Total Cost, Plan Rows, Plan Width, Filter and Index Cond, with child nodes under Plans; Plan Rows and Total Cost come from the same estimates as the text form (source: src/plan/explain.rs, render_json_node, render_json, explain_plan_json_ctx). Tested by test_explain_json_node_type, test_explain_json_aggregate and test_explain_ctx_json_index_scan.

EXPLAIN ANALYZE

With analyze, execute_explain renders the plan as above, then executes the inner plan with execute_plan, timing it with std::time::Instant (source: src/query/engine.rs, execute_explain; src/plan/explain.rs, append_analyze_suffix).

  • The statement really runs. EXPLAIN ANALYZE INSERT/UPDATE/DELETE changes data, as in PostgreSQL.
  • execute_plan applies RLS, view expansion, subquery resolution and scan filter pushdown to the inner plan, but not natural-join resolution, WHERE equi-join promotion or the optimizer. The executed plan can therefore differ from the one a plain execution of the same statement would run.
  • Text: the first line gets ` (actual time=E/2..E rows=N loops=1), where E is the elapsed milliseconds and N the result row count (or affected rows for DML). The start time is always half the total, not a measurement. Two lines follow: Planning Time: 0.1 ms, a constant, and Execution Time: E ms`.
  • JSON: Actual Rows, Actual Total Time, Actual Loops (1), Planning Time (0.1) and Execution Time are added inside the top Plan object. PostgreSQL puts Planning Time and Execution Time beside Plan, not inside it.
  • Only the root node gets actual numbers; child nodes have none.

Tested by test_explain_analyze_suffix in src/plan/explain.rs (the suffix format only). Not verified: no test runs EXPLAIN ANALYZE through the engine, and the effect of the skipped rewrites (for example on a NATURAL JOIN) is untested.

Per wire

Wire EXPLAIN behaviour
PostgreSQL engine output as above; treated as a read statement; command tag EXPLAIN (source: src/protocol/postgres/mod.rs). Tested by the statement list in src/protocol/postgres/mod.rs (EXPLAIN SELECT 1) and src/protocol/postgres/catalog.rs (EXPLAIN SELECT * FROM pg_class). See PostgreSQL
MySQL EXPLAIN [FORMAT=TRADITIONAL] before SELECT, UPDATE, DELETE, INSERT, REPLACE, WITH, TABLE or ( is converted to MySQL's 12-column table (see below). EXPLAIN ANALYZE, FORMAT=JSON, FORMAT=TREE and EXPLAIN <table> return the engine's output unchanged (source: src/protocol/mysql/explain.rs, wants_table, to_mysql; src/protocol/mysql/mod.rs, mysql_explain). Tested by which_statements and converts_plans
SQLite / libSQL (Hrana) error EXPLAIN is not supported (source: src/protocol/sqlite/hrana.rs)
MongoDB explain command answers ok with an empty queryPlanner; see MongoDB
Neo4j Bolt, Gremlin EXPLAIN/PROFILE and explain()/profile() not supported; see Neo4j Bolt, Gremlin
InfluxDB accepted, returns an empty result; see InfluxDB
Redis FT.EXPLAIN not handled; see Redis
CouchDB _explain is served by the Mango find code with explain set; it is not this renderer (source: src/protocol/couchdb/api.rs)
Elasticsearch _explain route, unrelated to SQL plans (source: src/protocol/elasticsearch/mod.rs)
Arrow Flight SQL, HTTP EXPLAIN is classified as a read statement and passed to the engine (source: src/protocol/arrow/flight_sql.rs; src/protocol/http/routes.rs)
SQL Server, Oracle, Snowflake, ClickHouse no EXPLAIN, SHOWPLAN or EXPLAIN PLAN handling in the wire code; Not verified: whether the text reaches the engine depends on each wire's statement routing

MySQL conversion

to_mysql reads the engine's text lines and builds rows with the columns id, select_type, table, partitions, type, possible_keys, key, key_len, ref, rows (int8), filtered (float8) and Extra (source: src/protocol/mysql/explain.rs, to_mysql).

Engine line MySQL type
Seq Scan ALL
Index Only Scan index
Index Scan ref; const when the key is the primary key
Bitmap Heap Scan range

An index name ending in _pkey is shown as PRIMARY; a Filter line adds Using where to Extra; rows is taken from the rows= figure. The engine never prints Index Only Scan or Bitmap Heap Scan, so index and range do not occur in practice (source: src/plan/explain.rs, explain_plan_text_ctx).