EXPLAIN
EXPLAIN — показать план выполнения оператора
Синтаксис
EXPLAIN [ (параметр[, ...] ) ]операторЗдесь допускаетсяпараметр: 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 }
Описание
Эта команда выводит план выполнения, генерируемый планировщиком Postgres Pro Shardman для заданного оператора. План выполнения показывает, как будут сканироваться таблицы, затрагиваемые оператором — просто последовательно, по индексу и т. д. — а если запрос связывает несколько таблиц, какой алгоритм соединения будет выбран для объединения считанных из них строк.
Наибольший интерес в выводимой информации представляет ожидаемая стоимость выполнения оператора, которая показывает, сколько, по мнению планировщика, будет выполняться этот оператор (это значение измеряется в единицах стоимости, которые не имеют точного определения, но обычно это обращение к странице на диске). Фактически выводятся два числа: стоимость запуска до выдачи первой строки и общая стоимость выдачи всех строк. Для большинства запросов важна общая стоимость, но в таких контекстах, как подзапрос в EXISTS, планировщик будет минимизировать стоимость запуска, а не общую стоимость (так как исполнение запроса всё равно завершится сразу после получения одной строки). Кроме того, если количество возвращаемых строк ограничивается предложением LIMIT, планировщик интерполирует стоимость между двумя этими числами, выбирая наиболее выгодный план.
С параметром ANALYZE оператор будет выполнен на самом деле, а не только запланирован. При этом в вывод добавляются фактические сведения о времени выполнения, включая общее время, затраченное на каждый узел плана (в миллисекундах) и общее число строк, выданных в результате. Это помогает понять, насколько близки к реальности предварительные оценки планировщика.
Важно
Имейте в виду, что с указанием ANALYZE оператор действительно выполняется. Хотя EXPLAIN отбрасывает результат, который вернул бы SELECT, в остальном все действия выполняются как обычно. Если вы хотите выполнить EXPLAIN ANALYZE с командой INSERT, UPDATE, DELETE, MERGE, CREATE TABLE AS или EXECUTE, не допуская изменения данных этой командой, воспользуйтесь таким приёмом:
BEGIN; EXPLAIN ANALYZE ...; ROLLBACK;
Параметры
ANALYZEВыполнить команду и вывести фактическое время выполнения и другую статистику. По умолчанию этот параметр равен
FALSE.VERBOSEВывести дополнительную информацию о плане запроса. В частности, включить список столбцов результата для каждого узла в дереве плана, дополнить схемой имена таблиц и функций, всегда указывать для переменных в выражениях псевдоним их таблицы, а также выводить имена всех триггеров, для которых выдаётся статистика. Также для данного запроса будет выводиться идентификатор, если он был вычислен; за подробностями обратитесь к compute_query_id. По умолчанию этот параметр равен
FALSE.COSTSВывести рассчитанную стоимость запуска и общую стоимость каждого узла плана, а также рассчитанное число строк и ширину каждой строки. Этот параметр по умолчанию равен
TRUE.SETTINGSВывести информацию о параметрах конфигурации. А именно, будут выведены параметры, влияющие на планирование, значения которых отличаются от стандартных значений по умолчанию. В отсутствие данного указания подразумевается
FALSE(эта информация не выводится).GENERIC_PLANИспользовать операторы с шаблонами параметров в виде
$1и создать общий план, не зависящий от значений параметров. За подробной информацией об общих планах и типах операторов, поддерживающих параметры, обратитесь кPREPARE. Этот параметр нельзя использовать сANALYZE. Значение по умолчанию —FALSE.BUFFERSВключить информацию об использовании буфера. В частности, вывести число попаданий, блоков прочитанных, загрязнённых и записанных в общем буфере, число попаданий, блоков прочитанных, загрязнённых и записанных в локальном буфере, число прочитанных и записанных временных блоков, а также время в миллисекундах, потраченное на чтение и запись блоков файлов данных, локальных блоков и блоков временных файлов, если включён параметр track_io_timing. Попаданием (hit) считается ситуация, когда требуемый блок уже находится в кеше и чтения с диска удаётся избежать. Блоки в общем буфере содержат данные обычных таблиц и индексов, в локальном — данные временных таблиц и индексов, а временные блоки предназначены для краткосрочного использования при выполнении сортировки, хеширования, материализации и подобных узлов плана. Число загрязнённых блоков (dirtied) показывает, сколько ранее не модифицированных блоков изменила данная операция; тогда как число записанных блоков (written) показывает, сколько ранее загрязнённых блоков данный серверный процесс вынес из кеша при обработке запроса. Значения, указываемые для узла верхнего уровня, включают значения всех его дочерних узлов. В текстовом формате выводятся только ненулевые значения. По умолчанию его значение равно
FALSE.SERIALIZEВключить информацию о стоимости сериализации выходных данных запроса, преобразовывая её в текстовый или двоичный формат для отправки клиенту. Это может занять значительную часть времени обычной работы запроса, если функции вывода типа данных дорогие или если необходимо вывести значения в формате TOAST из отдельного хранилища. При значении по умолчанию,
SERIALIZE NONE, эти преобразования не происходят. При заданных значенияхSERIALIZE TEXTилиSERIALIZE BINARYнеобходимое преобразование происходит, а затраченное время оценивается (если не задано значениеTIMING OFF). Если указан параметрBUFFERS, в стоимость также включаются обращения к буферам, участвующим в преобразовании. При этом командаEXPLAINникогда не отправляет полученные данные клиенту, поэтому стоимость передачи по сети таким образом рассчитать нельзя. Сериализация может работать только в режимеANALYZE. Если дляSERIALIZEне указан аргумент, подразумеваетсяTEXT.WALВключить информацию о формировании записей WAL. В частности, вывести число записей, число полных образов страниц (fpi, full page images) и объём сгенерированных записей в байтах. В текстовом формате выводятся только ненулевые значения. Этот параметр может использоваться, только если также включён режим
ANALYZE. По умолчанию он отключён (FALSE).TIMINGВключить в вывод фактическое время запуска и время, затраченное на каждый узел. Постоянное чтение системных часов может значительно замедлить запрос, так что если достаточно знать фактическое число строк, имеет смысл сделать этот параметр равным
FALSE. Время выполнения всего оператора замеряется всегда, даже когда этот параметр выключен и на уровне узлов время не подсчитывается. Этот параметр действует только в режимеANALYZE. По умолчанию его значение равноTRUE.SUMMARYВключить сводку (например, суммарное время) после плана запроса. Сводка включается по умолчанию, когда используется
ANALYZE, но этот параметр позволяет получить её и с другими вариантами команды. Время планирования вEXPLAIN EXECUTEвключает время извлечения плана из кеша и время перепланирования, если оно потребовалось.MEMORYВывести информацию о потреблении памяти на этапе планирования запросов. А именно, выводить точный объём памяти, используемый структурами данных в оперативной памяти, а также её общий объём с учётом издержек на выделение. Значение по умолчанию:
FALSE.FORMATУстановить один из следующих форматов вывода: TEXT, XML, JSON или YAML. Последние три формата содержат ту же информацию, что и текстовый, но больше подходят для программного разбора. По умолчанию выбирается формат
TEXT.booleanВключает или отключает заданный параметр. Для включения параметра можно написать
TRUE,ONили1, а для отключения —FALSE,OFFили0. Значениеbooleanможно опустить, в этом случае подразумеваетсяTRUE.операторЛюбой оператор
SELECT,INSERT,UPDATE,DELETE,MERGE,VALUES,EXECUTE,DECLARE,CREATE TABLE ASиCREATE MATERIALIZED VIEW AS, план выполнения которого вас интересует.
Выводимая информация
Результатом команды будет текстовое описание плана, выбранного для оператора, возможно, дополненное статистикой выполнения. Представленная информация описана в Разделе 14.1.
Примечания
Чтобы планировщик запросов Postgres Pro Shardman был достаточно информирован для эффективной оптимизации запросов, данные в pg_statistic должны быть актуальными для всех таблиц, задействованных в запросе. Обычно об этом автоматически заботится демон автоочистки. Но если в таблице недавно произошли значительные изменения, может потребоваться вручную выполнить ANALYZE, не дожидаясь, пока автоочистка обработает эти изменения.
Измеряя фактическую стоимость выполнения каждого узла в плане, текущая реализация EXPLAIN ANALYZE привносит накладные расходы профилирования в выполнение запроса. В результате этого, при запуске запроса командой EXPLAIN ANALYZE он может выполняться значительно дольше, чем при обычном выполнении. Объём накладных расходов зависит от природы запроса, а также от используемой платформы. Худшая ситуация наблюдается для узлов плана, которые сами по себе выполняются очень быстро, и в операционных системах, где получение текущего времени относительно длительная операция.
Примеры
Получение плана простого запроса для таблицы, содержащей единственный столбец типа integer, с 10000 строк:
EXPLAIN SELECT * FROM foo;
QUERY PLAN
---------------------------------------------------------
Seq Scan on foo (cost=0.00..155.00 rows=10000 width=4)
(1 row)План того же запроса, но выведенный в формате JSON:
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)Если в таблице есть индекс, а в запросе присутствует условие WHERE, для которого полезен этот индекс, EXPLAIN может показать другой план:
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)План того же запроса, но в формате YAML:
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 оставлено в качестве упражнения для читателя.
План того же запроса без вывода оценок стоимости:
EXPLAIN (COSTS FALSE) SELECT * FROM foo WHERE i = 4;
QUERY PLAN
----------------------------
Index Scan using fi on foo
Index Cond: (i = 4)
(2 rows)Пример плана для запроса с агрегатной функцией:
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)Пример использования EXPLAIN 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=10.77..10.87 rows=10 width=12) (actual time=0.043..0.044 rows=10 loops=1)
Group Key: foo
Batches: 1 Memory Usage: 24kB
-> Index Scan using test_pkey on test (cost=0.29..10.27 rows=99 width=8) (actual time=0.009..0.025 rows=99 loops=1)
Index Cond: ((id > 100) AND (id < 200))
Planning Time: 0.244 ms
Execution Time: 0.073 ms
(7 rows)Разумеется, конкретные числа, показанные здесь, зависят от фактического содержимого задействованных таблиц. Также учтите, что эти числа и даже выбранная стратегия выполнения запроса могут меняться от версии к версии Postgres Pro Shardman вследствие усовершенствования планировщика. Кроме того, команда ANALYZE при обработке статистических данных производит случайные выборки, так что оценки стоимости могут меняться при каждом чистом запуске ANALYZE, даже когда фактическое распределение данных в таблице не меняется.
Обратите внимание, что в предыдущем примере показан «специализированный» план для запроса EXECUTE с определёнными значениями параметров. С помощью 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) В этом случае анализатор запроса корректно предполагает, что $1 и $2 должны иметь тот же тип данных, что и id, так что отсутствие информации о типе данных из PREPARE не представляет проблемы. В других случаях может потребоваться явно указать типы для символов параметров, что можно сделать путём приведения типов, например:
EXPLAIN (GENERIC_PLAN)
SELECT sum(bar) FROM test
WHERE id > $1::integer AND id < $2::integer
GROUP BY foo;Совместимость
Оператор EXPLAIN отсутствует в стандарте SQL.
До версии Postgres Pro Shardman 9.0 использовался и по-прежнему поддерживается следующий синтаксис
EXPLAIN [ ANALYZE ] [ VERBOSE ] оператор
Обратите внимание, что параметры должны быть заданы именно в указанном порядке.
См. также
ANALYZEEXPLAIN
EXPLAIN — show the execution plan of a statement
Synopsis
EXPLAIN [ (option[, ...] ) ]statementwhereoptioncan 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
This command displays the execution plan that the Postgres Pro Shardman planner generates for the supplied statement. The execution plan shows how the table(s) referenced by the statement will be scanned — by plain sequential scan, index scan, etc. — and if multiple tables are referenced, what join algorithms will be used to bring together the required rows from each input table.
The most critical part of the display is the estimated statement execution cost, which is the planner's guess at how long it will take to run the statement (measured in cost units that are arbitrary, but conventionally mean disk page fetches). Actually two numbers are shown: 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 what matters, but in contexts such as a subquery in EXISTS, the planner will choose the smallest start-up cost instead of the smallest total cost (since the executor will stop after getting one row, anyway). Also, if you limit the number of rows to return with a LIMIT clause, the planner makes an appropriate interpolation between the endpoint costs to estimate which plan is really the cheapest.
The ANALYZE option causes the statement to be actually executed, not only planned. Then actual run time statistics are added to the display, including the total elapsed time expended within each plan node (in milliseconds) and the total number of rows it actually returned. This is useful for seeing whether the planner's estimates are close to reality.
Important
Keep in mind that the statement is actually executed when the ANALYZE option is used. Although EXPLAIN will discard 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, use this approach:
BEGIN; EXPLAIN ANALYZE ...; ROLLBACK;
Parameters
ANALYZECarry out the command and show actual run times and other statistics. This parameter defaults to
FALSE.VERBOSEDisplay additional information regarding 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, see compute_query_id for more details. This parameter defaults to
FALSE.COSTSInclude information on the estimated startup and total cost of each plan node, as well as the estimated number of rows and the estimated width of each row. This parameter defaults to
TRUE.SETTINGSInclude information on configuration parameters. Specifically, include options affecting query planning with value different from the built-in default value. This parameter defaults to
FALSE.GENERIC_PLANAllow the statement to contain parameter placeholders like
$1, and generate a generic plan that does not depend on the values of those parameters. SeePREPAREfor details about generic plans and the types of statement that support parameters. This parameter cannot be used together withANALYZE. It defaults toFALSE.BUFFERSInclude information on buffer usage. Specifically, include 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) if track_io_timing is enabled. A hit means that a read was avoided because the block was found already in cache when 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, Materialize plan nodes, and similar cases. The number of blocks dirtied indicates the number of previously unmodified blocks that were changed by this query; while the number of blocks written indicates the number of previously-dirtied blocks 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. This parameter defaults to
FALSE.SERIALIZEInclude information 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 are 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.WALInclude information on WAL record generation. Specifically, include the number of records, number of full page images (fpi) and the amount of WAL generated in bytes. In text format, only non-zero values are printed. This parameter may only be used when
ANALYZEis also enabled. It defaults toFALSE.TIMINGInclude 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 to
FALSEwhen only actual row counts, and not exact times, are needed. 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. It defaults toTRUE.SUMMARYInclude summary information (e.g., totaled timing information) after the query plan. Summary information is included by default when
ANALYZEis used but otherwise is not included by default, but can be enabled using 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.MEMORYInclude information on memory consumption by the query planning phase. Specifically, include the precise amount of storage used by planner in-memory structures, as well as total memory considering allocation overhead. This parameter defaults to
FALSE.FORMATSpecify the output format, which can be TEXT, XML, JSON, or YAML. Non-text output contains the same information as the text output format, but is easier for programs to parse. This parameter defaults to
TEXT.booleanSpecifies whether the selected option should be turned on or off. You can write
TRUE,ON, or1to enable the option, andFALSE,OFF, or0to disable it. Thebooleanvalue can also be omitted, in which caseTRUEis assumed.statementAny
SELECT,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
In order to allow the Postgres Pro Shardman 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 will take care of that automatically. 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.
In order to measure 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. The amount of overhead depends on the nature of the query, as well as the platform being used. The worst case occurs 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.
Examples
To show the plan for a simple query on a table with a single integer column and 10000 rows:
EXPLAIN SELECT * FROM foo;
QUERY PLAN
---------------------------------------------------------
Seq Scan on foo (cost=0.00..155.00 rows=10000 width=4)
(1 row)
Here is the same query, with 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)
If there is an index and we use a query with an indexable WHERE condition, EXPLAIN might show a different plan:
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)
Here is the same query, but in YAML 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)
XML format is left as an exercise for the reader.
Here is the same plan with cost estimates suppressed:
EXPLAIN (COSTS FALSE) SELECT * FROM foo WHERE i = 4;
QUERY PLAN
----------------------------
Index Scan using fi on foo
Index Cond: (i = 4)
(2 rows)
Here is an example of a query plan for a query using 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)
Here is 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 loops=1)
Group Key: foo
Batches: 1 Memory Usage: 24kB
-> Index Scan using test_pkey on test (cost=0.29..10.27 rows=99 width=8) (actual time=0.009..0.025 rows=99 loops=1)
Index Cond: ((id > 100) AND (id < 200))
Planning Time: 0.244 ms
Execution Time: 0.073 ms
(7 rows)
Of course, the specific numbers shown here depend on the actual contents of the tables involved. Also note that the numbers, and even the selected query strategy, might vary between Postgres Pro Shardman releases due to planner improvements. In addition, the ANALYZE command uses random sampling to estimate data statistics; therefore, it is possible for cost estimates to change after a fresh run of ANALYZE, even if the actual distribution of data in the table has not changed.
Notice that the previous example showed a “custom” plan for the specific parameter values given in EXECUTE. We might also wish to see the generic plan for a parameterized query, which can be done 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. In other cases it might be necessary to explicitly specify types for the parameter symbols, which can be done by casting them, for example:
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.
The following syntax was used before Postgres Pro Shardman 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.