EXPLAIN(7)
EXPLAIN(7) โ PostgreSQL 18.6 Documentation ๐
okay bestie, welcome to the EXPLAIN page, aka the moment your query tells you the truth about itself. this is section 7 of the PostgreSQL 18.6 manual and we are gonna read it together, no skimming, no skipping. ๐ซถ
โจ NAME โจ
EXPLAIN โ show the execution plan of a statement ๐
โจ SYNOPSIS โจ
EXPLAIN [ ( option [, ...] ) ] statement
where option can be one of:
ANALYZE [ boolean ]
VERBOSE [ boolean ]
COSTS [ boolean ]
SETTINGS [ boolean ]
GENERIC_PLAN [ boolean ]
BUFFERS [ boolean ]
SERIALIZE [ { NONE | TEXT | BINARY } ]
WAL [ boolean ]
TIMING [ boolean ]
SUMMARY [ boolean ]
MEMORY [ boolean ]
FORMAT { TEXT | XML | JSON | YAML }
โจ DESCRIPTION โจ
so like, this command displays the execution plan that the PostgreSQL planner cooked up for the statement you gave it. the plan shows you how the table(s) your statement references are gonna get scanned โ plain sequential scan, index scan, etc. โ and if more than one table is in the mix, it also shows you which join algorithms are getting used to bring together the rows each input table needs to contribute. it's giving behind-the-scenes documentary. ๐ฌ
the most critical part of the whole display is the estimated statement execution cost, which is basically the planner's best guess at how long the statement will take to run (measured in cost units that are arbitrary, but conventionally mean disk page fetches). and actually there are two numbers, not one: the start-up cost before the first row can be returned, and the total cost to return all the rows. for most queries the total cost is the one that matters, but in contexts like a subquery inside EXISTS, the planner picks the smallest start-up cost instead of the smallest total cost (because the executor is gonna stop after it gets one row anyway, so why pay for more?). also, if you cap the number of rows to return with a LIMIT clause, the planner makes an appropriate interpolation between the endpoint costs to figure out which plan is really the cheapest. math girlies stay winning. ๐
the ANALYZE option makes the statement actually execute, not just get planned. then actual run time statistics get added to the display, including the total elapsed time spent within each plan node (in milliseconds) and the total number of rows it actually returned. super useful for vibe-checking whether the planner's estimates are anywhere close to reality. ๐
Important ๐จ keep in mind that the statement is actually executed when theANALYZEoption is used. althoughEXPLAINwill discard any output that aSELECTwould return, other side effects of the statement will happen as usual. if you wish to useEXPLAIN ANALYZEon anINSERT,UPDATE,DELETE,MERGE,CREATE TABLE AS, orEXECUTEstatement without letting the command affect your data, use this approach:text BEGIN; EXPLAIN ANALYZE ...; ROLLBACK;protect your data bestie, she's fragile ๐ญ
โจ PARAMETERS โจ
ANALYZEโ carry out the command and show actual run times and other statistics. this one defaults toFALSE.VERBOSEโ display extra info about the plan. specifically: include the output column list for each node in the plan tree, schema-qualify table and function names, always label variables in expressions with their range table alias, and always print the name of each trigger for which statistics are displayed. the query identifier will also be displayed if one has been computed, seecompute_query_idfor more details. defaults toFALSE.COSTSโ include info on the estimated startup and total cost of each plan node, plus the estimated number of rows and the estimated width of each row. this one defaults toTRUE.SETTINGSโ include info on configuration parameters. specifically, include options affecting query planning whose value differs from the built-in default value. defaults toFALSE.GENERIC_PLANโ allow the statement to contain parameter placeholders like$1, and generate a generic plan that doesn't depend on the values of those parameters. seePREPAREfor details about generic plans and which types of statement support parameters. this parameter cannot be used together withANALYZE. defaults toFALSE.BUFFERSโ include info on buffer usage. specifically: the number of shared blocks hit, read, dirtied, and written; the number of local blocks hit, read, dirtied, and written; the number of temp blocks read and written; and the time spent reading and writing data file blocks, local blocks and temporary file blocks (in milliseconds) iftrack_io_timingis enabled. a hit means a read was avoided because the block was already sitting in cache when it was needed. shared blocks contain data from regular tables and indexes; local blocks contain data from temporary tables and indexes; while temporary blocks contain short-term working data used in sorts, hashes,Materializeplan nodes, and similar cases. the number of blocks dirtied is how many previously unmodified blocks this query changed; while the number of blocks written is how many previously-dirtied blocks got evicted from cache by this backend during query processing. the number of blocks shown for an upper-level node includes those used by all its child nodes. in text format, only non-zero values are printed. buffers info is automatically included whenANALYZEis used. โจSERIALIZEโ include info on the cost of serializing the query's output data, that is, converting it to text or binary format to send to the client. this can be a significant part of the time required for regular execution of the query, if the datatype output functions are expensive or if TOASTed values must be fetched from out-of-line storage.EXPLAIN's default behavior,SERIALIZE NONE, does not perform these conversions. ifSERIALIZE TEXTorSERIALIZE BINARYis specified, the appropriate conversions are performed and the time spent doing so is measured (unlessTIMING OFFis specified). if theBUFFERSoption is also specified, then any buffer accesses involved in the conversions get counted too. in no case, however, willEXPLAINactually send the resulting data to the client โ hence network transmission costs cannot be investigated this way. serialization may only be enabled whenANALYZEis also enabled. ifSERIALIZEis written without an argument,TEXTis assumed.WALโ include info on WAL record generation. specifically: the number of records, the number of full page images (fpi), the amount of WAL generated in bytes, and the number of times the WAL buffers became full. in text format, only non-zero values are printed. this parameter may only be used whenANALYZEis also enabled. defaults toFALSE.TIMINGโ include actual startup time and time spent in each node in the output. the overhead of repeatedly reading the system clock can slow down the query significantly on some systems, so it may be useful to set this parameter toFALSEwhen you only need actual row counts and not exact times. run time of the entire statement is always measured, even when node-level timing is turned off with this option. this parameter may only be used whenANALYZEis also enabled. defaults toTRUE.SUMMARYโ include summary information (e.g., totaled timing information) after the query plan. summary info is included by default whenANALYZEis used, but otherwise it isn't included by default โ though you can turn it on with this option. planning time inEXPLAIN EXECUTEincludes the time required to fetch the plan from the cache and the time required for re-planning, if necessary.MEMORYโ include info on memory consumption by the query planning phase. specifically: the precise amount of storage used by planner in-memory structures, as well as total memory considering allocation overhead. defaults toFALSE.FORMATโ specify the output format, which can beTEXT,XML,JSON, orYAML. non-text output contains the same information as the text output format, but it's easier for programs to parse. defaults toTEXT.booleanโ specifies whether the selected option should be turned on or off. you can writeTRUE,ON, or1to enable the option, andFALSE,OFF, or0to disable it. the boolean value can also be omitted, in which caseTRUEis assumed.statementโ anySELECT,INSERT,UPDATE,DELETE,MERGE,VALUES,EXECUTE,DECLARE,CREATE TABLE AS, orCREATE MATERIALIZED VIEW ASstatement whose execution plan you wish to see.
โจ OUTPUTS โจ
the command's result is a textual description of the plan selected for the statement, optionally annotated with execution statistics. Section 14.1 describes the information provided. ๐โจ
โจ NOTES โจ
so for the PostgreSQL query planner to make reasonably informed decisions when optimizing queries, the pg_statistic data should be up-to-date for all tables used in the query. normally the autovacuum daemon handles that automatically, no stress. but if a table has recently had substantial changes in its contents, you might need to do a manual ANALYZE rather than wait for autovacuum to catch up with the changes. don't just sit there waiting bestie, run it ๐
and for measuring the run-time cost of each node in the execution plan: the current implementation of EXPLAIN ANALYZE adds profiling overhead to query execution. as a result, running EXPLAIN ANALYZE on a query can sometimes take significantly longer than executing the query normally. how much overhead depends on the nature of the query and on the platform you're on. the worst case happens for plan nodes that in themselves require very little time per execution, and on machines that have relatively slow operating system calls for obtaining the time of day. ๐ญ the clock is the enemy fr fr
๐ EXAMPLES ๐
Okay bestie, this is the part where it all clicks. Let's look at some actual plans together. ๐ซถ
So, first up: a super simple query on a table with a single integer column and 10000 rows. Watch this:
EXPLAIN SELECT * FROM foo;
QUERY PLAN
---------------------------------------------------------
Seq Scan on foo (cost=0.00..155.00 rows=10000 width=4)
(1 row)
Same exact query, but now we're asking for JSON output formatting:
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)
Now if there's an index and our WHERE condition is actually indexable, EXPLAIN might show you a whole different plan. It's giving glow-up:
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)
And here's that same query, but in YAML format (for the yaml girlies โจ):
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)
XML format is left as an exercise for the reader. ๐ (not me making you do homework, iykyk)
Here's the same plan but with the cost estimates suppressed, so no numbers, just vibes:
EXPLAIN (COSTS FALSE) SELECT * FROM foo WHERE i = 4;
QUERY PLAN
---------------------------
Index Scan using fi on foo
Index Cond: (i = 4)
(2 rows)
Okay now an example of a query plan for a query that uses an aggregate function:
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)
And here's an example of using EXPLAIN EXECUTE to display the execution plan for a prepared query:
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=10.77..10.87 rows=10 width=12) (actual time=0.043..0.044 rows=10.00 loops=1)
Group Key: foo
Batches: 1 Memory Usage: 24kB
Buffers: shared hit=4
-> Index Scan using test_pkey on test (cost=0.29..10.27 rows=99 width=8) (actual time=0.009..0.025 rows=99.00 loops=1)
Index Cond: ((id > 100) AND (id < 200))
Index Searches: 1
Buffers: shared hit=4
Planning Time: 0.244 ms
Execution Time: 0.073 ms
(10 rows)
Bestie, real talk: the specific numbers you see here depend on the actual contents of the tables involved. Also, heads up โ the numbers, and even the query strategy that gets picked, might vary between PostgreSQL releases because of planner improvements. And on top of that, theANALYZEcommand uses random sampling to estimate data statistics, so it's totally possible for cost estimates to change after a fresh run ofANALYZE, even if the actual distribution of data in the table hasn't changed at all. No cap. ๐ซ
Okay so notice how that last example showed a "custom" plan for the specific parameter values given in EXECUTE? Yeah. So we might also want to see the generic plan for a parameterized query โ and you can do that with GENERIC_PLAN:
EXPLAIN (GENERIC_PLAN)
SELECT sum(bar) FROM test
WHERE id > $1 AND id < $2
GROUP BY foo;
QUERY PLAN
---------------------------------------------------------------------------------------
HashAggregate (cost=26.79..26.89 rows=10 width=12)
Group Key: foo
-> Index Scan using test_pkey on test (cost=0.29..24.29 rows=500 width=8)
Index Cond: ((id > $1) AND (id < $2))
(4 rows)
In this case the parser correctly inferred that $1 and $2 should have the same data type as id, so the lack of parameter type information from PREPARE was not a problem. But in other cases it might be necessary to explicitly specify types for the parameter symbols โ and you can do that by casting them, like so:
EXPLAIN (GENERIC_PLAN)
SELECT sum(bar) FROM test
WHERE id > $1::integer AND id < $2::integer
GROUP BY foo;
๐ COMPATIBILITY ๐
There is no EXPLAIN statement defined in the SQL standard. We're just built different, fr fr. ๐
The following syntax was used before PostgreSQL version 9.0 and is still supported:
EXPLAIN [ ANALYZE ] [ VERBOSE ] statement
โ ๏ธ Note that in this syntax, the options must be specified in exactly the order shown. No shuffling, no remixing. The order is the order. ๐
๐ SEE ALSO ๐
And that's the whole page, bestie!! Go forth and EXPLAIN everything. ๐
This one's from PostgreSQL 18.6, dated 2026, and it lives at EXPLAIN(7) โ mwah, iconic, periodt. ๐
โจ
๐ฆ where this page comes from
- opensuse-leap 16.0: postgresql18 18.6-160000.1.1 ยท PostgreSQL
- opensuse-leap 16.0: postgresql18 18.6-160000.1.1 ยท PostgreSQL
- opensuse-leap 16.0: postgresql18 18.6-160000.1.1 ยท PostgreSQL
- opensuse-leap 16.0: postgresql18 18.6-160000.1.1 ยท PostgreSQL
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms