EXPLAIN
EXPLAIN shows the execution plan that the PolarDB PostgreSQL query planner generates for a statement. Use it to understand how tables are scanned (sequential scan, index scan, etc.), which join algorithms are used, and how much each step costs — so you can identify slow queries and decide where to add indexes or rewrite SQL.
Synopsis
EXPLAIN [ ( option [, ...] ) ] statement
EXPLAIN [ ANALYZE ] [ VERBOSE ] statementwhere *option* can be one of:
ANALYZE [ boolean ]
VERBOSE [ boolean ]
COSTS [ boolean ]
SETTINGS [ boolean ]
GENERIC_PLAN [ boolean ]
BUFFERS [ boolean ]
WAL [ boolean ]
TIMING [ boolean ]
SUMMARY [ boolean ]
FORMAT { TEXT | XML | JSON | YAML }Description
EXPLAIN displays the execution plan for a statement without executing it. The output shows how the planner intends to scan each referenced table — by sequential scan, index scan, or another method — and, when multiple tables are involved, which join algorithm it will use.
The most important part of the output is the estimated cost, which represents the planner's estimate of how long the statement will take to run. Costs are measured in arbitrary units that conventionally correspond to disk page fetches. Two cost figures are shown for each plan node:
Startup cost: cost before the first row can be returned (e.g., time spent sorting in a sort node)
Total cost: cost to return all rows, assuming the node runs to completion
For most queries, total cost is what matters. In contexts such as a subquery in EXISTS, the planner chooses the smallest startup cost instead (because execution stops after the first row). With a LIMIT clause, the planner interpolates between the two cost figures to estimate the cheapest plan.
ANALYZE causes the statement to actually execute and adds real runtime statistics to the output: total elapsed time within each plan node (in milliseconds) and the actual number of rows returned. This makes it possible to see whether the planner's estimates are close to reality.
EXPLAIN ANALYZE actually executes the statement. Although EXPLAIN discards any output that a SELECT would return, other side effects of the statement will happen as usual. If you wish to use EXPLAIN ANALYZE on an INSERT, UPDATE, DELETE, MERGE, CREATE TABLE AS, or EXECUTE statement without letting the command affect your data, wrap it in a transaction:
BEGIN;
EXPLAIN ANALYZE ...;
ROLLBACK;Only ANALYZE and VERBOSE can be specified without parentheses, and only in that order.
Parameters
ANALYZE— Execute the statement and include actual run times and row counts. Defaults toFALSE.VERBOSE— Show additional plan details: the output column list for each plan node, schema-qualified table and function names, range table aliases on all variables, trigger names for which statistics are shown, and the query identifier (if computed). Defaults toFALSE.COSTS— Include estimated startup cost, total cost, row count, and row width for each plan node. Defaults toTRUE.SETTINGS— Include configuration parameters that affect query planning and have a non-default value. Defaults toFALSE.BUFFERS— Include buffer usage statistics: shared blocks hit, read, dirtied, and written; local blocks hit, read, dirtied, and written; temp blocks read and written; and time spent on I/O (in milliseconds, iftrack_io_timingis enabled).Hit: a read was avoided because the block was already in cache.
Shared blocks: regular tables and indexes.
Local blocks: temporary tables and indexes.
Temp blocks: short-term working data used in sorts, hashes, and Materialize nodes.
Blocks dirtied = previously unmodified blocks changed by this query.
Blocks written = previously-dirtied blocks evicted from cache during query processing.
In text format, only non-zero values are printed. Upper-level nodes include counts from all child nodes.
Defaults to
FALSE.
WAL— Include WAL (Write-Ahead Log) record generation statistics: number of records, number of full page images (fpi), and bytes generated. In text format, only non-zero values are printed. RequiresANALYZE. Defaults toFALSE.TIMING— Include actual startup time and time spent in each plan node. Reading the system clock repeatedly can slow queries on some platforms, so set this toFALSEwhen you need only row counts. The total statement runtime is always measured even when node-level timing is off. RequiresANALYZE. Defaults toTRUE.SUMMARY— Include summary information (e.g., total planning and execution time) after the query plan. Included by default whenANALYZEis used; otherwise off by default. ForEXPLAIN EXECUTE, planning time includes fetching the plan from the cache and re-planning if necessary.FORMAT— Output format:TEXT,XML,JSON, orYAML. Non-text formats contain the same information as text format but are easier to parse programmatically. Defaults toTEXT.boolean— Enable or disable the selected option. UseTRUE,ON, or1to enable;FALSE,OFF, or0to disable. If omitted,TRUEis assumed.statement— The statement to explain. Supported statement types:SELECT,INSERT,UPDATE,DELETE,MERGE,VALUES,EXECUTE,DECLARE,CREATE TABLE AS,CREATE MATERIALIZED VIEW AS.
Outputs
The command returns a textual description of the execution plan for the statement, optionally annotated with runtime statistics.
Usage notes
Keep statistics current. The PolarDB PostgreSQL query planner relies on pg_statistic to make good planning decisions. The autovacuum daemon normally keeps these statistics up to date, but if a table has had large recent changes, run ANALYZE manually rather than waiting for autovacuum.
EXPLAIN ANALYZE adds overhead. Profiling each plan node requires repeated system clock reads, which can make EXPLAIN ANALYZE take significantly longer than running the query directly. The overhead is highest for plan nodes that execute very quickly and on platforms with slow time-of-day calls.
Examples
All examples use the foo table, which has a single integer column (i) and 10,000 rows.
Sequential scan
Without a usable index, the planner chooses a sequential scan:
EXPLAIN SELECT * FROM foo; QUERY PLAN
---------------------------------------------------------
Seq Scan on foo (cost=0.00..155.00 rows=10000 width=4)
(1 row)The four numbers in parentheses mean:
| Field | Description |
|---|---|
0.00 (startup cost) | Cost before the first row can be returned |
155.00 (total cost) | Estimated cost to return all rows |
rows=10000 | Estimated number of rows output |
width=4 | Estimated average row width in bytes |
Index scan with a WHERE condition
When a selective WHERE condition matches an index, the planner switches to an index scan:
EXPLAIN SELECT * FROM foo WHERE i = 4; QUERY PLAN
--------------------------------------------------------------
Index Scan using fi on foo (cost=0.00..5.98 rows=1 width=4)
Index Cond: (i = 4)
(2 rows)The lower total cost (5.98 vs. 155.00) reflects that the planner expects to read only one row instead of all 10,000.
Suppress cost estimates
Use COSTS FALSE to get a clean structural view of the plan without cost numbers:
EXPLAIN (COSTS FALSE) SELECT * FROM foo WHERE i = 4; QUERY PLAN
----------------------------
Index Scan using fi on foo
Index Cond: (i = 4)
(2 rows)Aggregate function
The plan for a query with an aggregate shows two nodes — the outer Aggregate feeds from the inner Index Scan:
EXPLAIN SELECT sum(i) FROM foo WHERE i < 10; QUERY PLAN
-------------------------------------------------------------------
Aggregate (cost=23.93..23.93 rows=1 width=4)
-> Index Scan using fi on foo (cost=0.00..23.92 rows=6 width=4)
Index Cond: (i < 10)
(3 rows)JSON output format
Use FORMAT JSON to get machine-readable output:
EXPLAIN (FORMAT JSON) SELECT * FROM foo; QUERY PLAN
--------------------------------
[ +
{ +
"Plan": { +
"Node Type": "Seq Scan",+
"Relation Name": "foo", +
"Alias": "foo", +
"Startup Cost": 0.00, +
"Total Cost": 155.00, +
"Plan Rows": 10000, +
"Plan Width": 4 +
} +
} +
]
(1 row)YAML output format
EXPLAIN (FORMAT YAML) SELECT * FROM foo WHERE i='4'; QUERY PLAN
-------------------------------
- Plan: +
Node Type: "Index Scan" +
Scan Direction: "Forward"+
Index Name: "fi" +
Relation Name: "foo" +
Alias: "foo" +
Startup Cost: 0.00 +
Total Cost: 5.98 +
Plan Rows: 1 +
Plan Width: 4 +
Index Cond: "(i = 4)"
(1 row)Analyze a prepared statement
To profile a parameterized query, prepare it first, then run EXPLAIN ANALYZE EXECUTE:
PREPARE query(int, int) AS SELECT sum(bar) FROM test
WHERE id > $1 AND id < $2
GROUP BY foo;
EXPLAIN ANALYZE EXECUTE query(100, 200); QUERY PLAN
-----------------------------------------------------------------------------------------------------------------------------------
HashAggregate (cost=9.54..9.54 rows=1 width=8) (actual time=0.156..0.161 rows=11 loops=1)
Group Key: foo
-> Index Scan using test_pkey on test (cost=0.29..9.29 rows=50 width=8) (actual time=0.039..0.091 rows=99 loops=1)
Index Cond: ((id > $1) AND (id < $2))
Planning time: 0.197 ms
Execution time: 0.225 ms
(6 rows)The specific cost numbers depend on actual table contents. Numbers and selected strategies can vary across PostgreSQL releases due to planner improvements. Because ANALYZE uses random sampling to estimate statistics, cost estimates may change after a fresh ANALYZE run even if the data distribution has not changed.