バージョンごとのドキュメント一覧

EXPLAIN

EXPLAIN <refpurpose>show the execution plan of a statement</refpurpose> — 問い合わせ文の実行計画を表示する

概要

EXPLAIN [ ( option [, ...] ) ] statement
EXPLAIN [ ANALYZE ] [ VERBOSE ] statement


<phrase>where <replaceable class="parameter">option</replaceable> can be one of:</phrase>

ここでoptionは以下のいずれかを取ることができます。

    ANALYZE [ boolean ]
    VERBOSE [ boolean ]
    COSTS [ boolean ]
    SETTINGS [ boolean ]
    GENERIC_PLAN [ boolean ]
    BUFFERS [ boolean ]
    WAL [ boolean ]
    TIMING [ boolean ]
    SUMMARY [ boolean ]
    FORMAT { TEXT | XML | JSON | YAML }

説明

<title>Description</title>

This command displays the execution plan that the <productname>PostgreSQL</productname> planner generates for the supplied statement. The execution plan shows how the table(s) referenced by the statement will be scanned &mdash; by plain sequential scan, index scan, etc. &mdash; and if multiple tables are referenced, what join algorithms will be used to bring together the required rows from each input table. 与えられた文に対して、PostgreSQLプランナが生成する実行計画を表示します。 実行計画は、問い合わせ文が参照するテーブル(複数の場合もある)をスキャンする方法(単純なシーケンシャルスキャン、インデックススキャンなど)、複数のテーブルを参照する場合に、各テーブルから取り出した行を結合するために使用する結合アルゴリズムを示すものです。

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 <literal>EXISTS</literal>, 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 <literal>LIMIT</literal> clause, the planner makes an appropriate interpolation between the endpoint costs to estimate which plan is really the cheapest. 表示内容の中でも、最も重要なのは、文の実行にかかるコストの見積もりです。 これは、プランナが文の実行にかかる時間(任意の、しかし慣習的にはディスクページ抽出を意味するコスト単位で計測)を推測したものです。 具体的には、2つの数が表示されます。 1つは最初の行が返されるまでのスタートアップコスト、もう1つはすべての行が返されるまでの合計コストです。 ほとんどの問い合わせにとって問題となるのは合計コストの方ですが、EXISTS副問い合わせなどのコンテキストでは、プランナは合計コストが最も短くなるプランよりも、スタートアップコストが最も短くなるプランを選びます(エグゼキュータは行を1つ取得した後に停止するからです)。 また、LIMIT句を使って問い合わせが返す行数を制限する場合、プランナは実際にはどの計画が一番低コストになるかを概算するため、全体を処理した場合のコストの間で適切な補間を行います。

The <literal>ANALYZE</literal> 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. ANALYZEオプションを付けると、計画を作るだけでなく、文が実際に実行されます。 この場合は、各計画ノードで費された総経過時間(ミリ秒単位)と実際に返された全行数など、実際の実行時の統計情報が追加表示されます。 プランナの推測と実際の値が近いかどうかを確認するために、このオプションは有用です。

重要

Keep in mind that the statement is actually executed when the <literal>ANALYZE</literal> option is used. Although <command>EXPLAIN</command> will discard any output that a <command>SELECT</command> would return, other side effects of the statement will happen as usual. If you wish to use <command>EXPLAIN ANALYZE</command> on an <command>INSERT</command>, <command>UPDATE</command>, <command>DELETE</command>, <command>MERGE</command>, <command>CREATE TABLE AS</command>, or <command>EXECUTE</command> statement without letting the command affect your data, use this approach: ANALYZEを使用した場合は、文が実際に実行されることを忘れないでください。 EXPLAINSELECTが返す出力をまったく表示しませんが、文に伴う副作用は通常通り発生します。 INSERTUPDATEDELETEMERGECREATE TABLE ASEXECUTE文に対して、データに影響を与えないようにEXPLAIN ANALYZEを実行したい場合は、以下の方法を使用してください。

BEGIN;
EXPLAIN ANALYZE ...;
ROLLBACK;

Only the <literal>ANALYZE</literal> and <literal>VERBOSE</literal> options can be specified, and only in that order, without surrounding the option list in parentheses. Prior to <productname>PostgreSQL</productname> 9.0, the unparenthesized syntax was the only one supported. It is expected that all new options will be supported only in the parenthesized syntax. ANALYZEおよびVERBOSEオプションのみが、この順序でのみ、オプションリストを括弧で括ることなく、指定可能です。 PostgreSQL 9.0より前までは、括弧がない構文のみがサポートされていました。 すべての新しいオプションは括弧付き構文のみでサポートされることを想定しています。

パラメータ

<title>Parameters</title>
ANALYZE

Carry out the command and show actual run times and other statistics. This parameter defaults to <literal>FALSE</literal>. コマンドを実行し、実際の実行時間やその他の統計情報を表示します。 このパラメータのデフォルトはFALSEです。

VERBOSE

Display 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 <xref linkend="guc-compute-query-id"/> for more details. This parameter defaults to <literal>FALSE</literal>. 計画についての追加情報を出力します。 具体的には、計画ツリー、スキーマ修飾テーブル、関数名内の各ノードに対して出力列リストを含めます。 常に範囲テーブルの別名を付けて式内の変数を命名し、また常に統計情報が表示される各トリガの名前を出力します。 計算されていれば問い合わせ識別子も表示されます。詳細はcompute_query_idを参照してください。 このパラメータのデフォルトはFALSEです。

COSTS

Include 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 <literal>TRUE</literal>. 各計画ノードの推定起動コストと総コスト、さらに推定行数と各行の推定幅に関する情報を含めます。 このパラメータのデフォルトはTRUEです。

SETTINGS

Include information on configuration parameters. Specifically, include options affecting query planning with value different from the built-in default value. This parameter defaults to <literal>FALSE</literal>. 設定パラメータに関する情報を含めます。 特に、組み込みのデフォルト値と異なる値で問い合わせ計画に影響するオプションを含めます。 このパラメータのデフォルトはFALSEです。

GENERIC_PLAN

Allow the statement to contain parameter placeholders like <literal>$1</literal>, and generate a generic plan that does not depend on the values of those parameters. See <link linkend="sql-prepare"><command>PREPARE</command></link> for details about generic plans and the types of statement that support parameters. This parameter cannot be used together with <literal>ANALYZE</literal>. It defaults to <literal>FALSE</literal>. 文が$1のようなパラメータプレースホルダを含むことを許可し、これらのパラメータの値に依存しない汎用的な計画を生成します。 汎用的な計画およびパラメータをサポートする文のタイプの詳細は、PREPAREを参照してください。 このパラメータはANALYZEと併用できません。 デフォルトはFALSEです。

BUFFERS

Include 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 and temporary file blocks (in milliseconds) if <xref linkend="guc-track-io-timing"/> is enabled. A <emphasis>hit</emphasis> 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 <emphasis>dirtied</emphasis> indicates the number of previously unmodified blocks that were changed by this query; while the number of blocks <emphasis>written</emphasis> 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 <literal>FALSE</literal>. バッファの使用状況に関する情報を含めます。 具体的には、共有ブロックのヒット数、読み取り数、ダーティブロック数、書き出し数、ローカルブロックのヒット数、読み取り数、ダーティブロック数、書き出し数、一時ブロックの読み取り数、書き出し数、そして、track_io_timingが有効にされていればデータファイルブロックと一時ファイルブロックの読み取り、書き出しに掛かった時間(ミリ秒単位)が含められます。 ヒットとは、必要な時にキャッシュ内にそのブロックが見つかったため読み取りが避けられたことを意味します。 共有ブロックには、通常のテーブルとインデックスからのデータが含まれます。 ローカルブロックには、一時テーブルとそのインデックスからのデータが含まれます。 一時ブロックには、ソートやハッシュ、マテリアライズ計画ノードなどで使用される短期間有効なデータが含まれます。 ダーティブロック数は、これまでは変更がなかったがその問い合わせによって変更されたブロックの数を示します。 書き出しブロック数は、問い合わせ処理の間にバックエンドにより、ダーティ状態だったブロックの内キャッシュから追い出されたブロックの数を示します。 上位レベルのノードで表示されるブロック数には、その子ノードすべてで使用されるブロックが含まれます。 テキスト形式では、非ゼロの値のみが出力されます。 このパラメータのデフォルトはFALSEです。

WAL

Include 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 <literal>ANALYZE</literal> is also enabled. It defaults to <literal>FALSE</literal>. WALレコード生成に関する情報を含めます。 具体的には、レコード数、ページ全体のイメージ(fpi)の数、生成されたWALのバイト単位での量が含められます。 テキスト形式では、非ゼロの値のみが出力されます。 このパラメータはANALYZEパラメータも有効である場合にのみ使用できます。 デフォルトはFALSEです。

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 to <literal>FALSE</literal> when 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 when <literal>ANALYZE</literal> is also enabled. It defaults to <literal>TRUE</literal>. 実際のスタートアップ時間とノードで費やされた時間が追加表示されます。 一部のシステムでは、システムクロックを何度も読み取るオーバーヘッドのため問い合わせがかなり低速になる可能性があります。 このため、実際の時間ではなく実際の行数のみが必要であるのであれば、このパラメータはFALSEに設定する方が有益でしょう。 文全体の実行時間は、このオプションによってノードレベルの時間計測が無効であった場合であっても、常に計測されます。 このパラメータはANALYZEパラメータも有効である場合にのみ使用することができます。 デフォルトはTRUEです。

SUMMARY

Include summary information (e.g., totaled timing information) after the query plan. Summary information is included by default when <literal>ANALYZE</literal> is used but otherwise is not included by default, but can be enabled using this option. Planning time in <command>EXPLAIN EXECUTE</command> includes the time required to fetch the plan from the cache and the time required for re-planning, if necessary. 要約情報(例えば、時間の情報の合計)を問い合わせ計画の後に出力します。 要約情報はANALYZEが使われるときはデフォルトで含まれ、それ以外の場合はデフォルトでは含まれませんが、このオプションを使えば有効にできます。 EXPLAIN EXECUTEの計画時間には、計画をキャッシュから取得するのに要する時間、および必要なら再計画するのに要する時間も含まれます。

FORMAT

Specify 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 <literal>TEXT</literal>. 出力形式を指定します。 TEXT、XML、JSON、YAMLを指定可能です。 TEXT以外の出力にはTEXT出力と同じ情報が含まれていますが、プログラムによる解析がより容易になります。 このパラメータのデフォルトはTEXTです。

boolean

Specifies whether the selected option should be turned on or off. You can write <literal>TRUE</literal>, <literal>ON</literal>, or <literal>1</literal> to enable the option, and <literal>FALSE</literal>, <literal>OFF</literal>, or <literal>0</literal> to disable it. The <replaceable class="parameter">boolean</replaceable> value can also be omitted, in which case <literal>TRUE</literal> is assumed. 選択したオプションを有効とするか無効とするかを指定します。 オプションを有効にするためにはTRUEON1のいずれかを書きます。 無効にするにはFALSEOFF0のいずれかを書きます。 boolean値は省略可能です。 省略時はTRUEとみなされます。

statement

Any <command>SELECT</command>, <command>INSERT</command>, <command>UPDATE</command>, <command>DELETE</command>, <command>MERGE</command>, <command>VALUES</command>, <command>EXECUTE</command>, <command>DECLARE</command>, <command>CREATE TABLE AS</command>, or <command>CREATE MATERIALIZED VIEW AS</command> statement, whose execution plan you wish to see. 実行計画の表示対象となる、SELECTINSERTUPDATEDELETEMERGEVALUESEXECUTEDECLARECREATE TABLE ASCREATE MATERIALIZED VIEW ASのいずれかの文です。

出力

<title>Outputs</title>

The command's result is a textual description of the plan selected for the <replaceable class="parameter">statement</replaceable>, optionally annotated with execution statistics. <xref linkend="using-explain"/> describes the information provided. コマンドの結果は、statementに対して選択された計画をテキストで説明します。 オプションで、実行時の統計情報で注釈が付けられます。 14.1では出力される情報について説明します。

注釈

<title>Notes</title>

In order to allow the <productname>PostgreSQL</productname> query planner to make reasonably informed decisions when optimizing queries, the <link linkend="catalog-pg-statistic"><structname>pg_statistic</structname></link> data should be up-to-date for all tables used in the query. Normally the <link linkend="autovacuum">autovacuum daemon</link> 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 <link linkend="sql-analyze"><command>ANALYZE</command></link> rather than wait for autovacuum to catch up with the changes. PostgreSQL問い合わせプランナが十分な情報を使って問合せを最適化できるようにするには、問い合わせ内で使用されるすべてのテーブルに関するpg_statisticのデータを最新状態にしなければなりません。 通常自動バキュームデーモンにより自動的に処理されます。 しかし最近その内容が大きく変更されたテーブルでは、自動バキュームがその変更に追いつくまで待つのではなく、手作業によるANALYZEを実行する必要があるかもしれません。

In order to measure the run-time cost of each node in the execution plan, the current implementation of <command>EXPLAIN ANALYZE</command> adds profiling overhead to query execution. As a result, running <command>EXPLAIN ANALYZE</command> 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. 実行計画内の各ノードの実行時コストを測定するために、現在のEXPLAIN ANALYZE実装は、問い合わせ実行に対し、情報収集のためのオーバーヘッドを加えます。 この結果、ある問い合わせについてのEXPLAIN ANALYZE実行が、普通に問い合わせを実行した場合より非常に時間がかかることがあります。 このオーバーヘッドの量は問い合わせの性質と使用するプラットフォームに依存します。 実行の間非常に短い時間を必要とする計画ノードに関して、時刻を得るためのシステムコールの操作が相対的に低速なプラットフォーム上で最悪な場合が発生します。

<title>Examples</title>

To show the plan for a simple query on a table with a single <type>integer</type> column and 10000 rows: integer列を1つ持ち、10000行が存在するテーブルに対して、単純な問い合わせを行った場合の問い合わせ計画を表示します。

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: 以下は同じ問い合わせを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)

If there is an index and we use a query with an indexable <literal>WHERE</literal> condition, <command>EXPLAIN</command> might show a different plan: インデックスが存在し、問い合わせの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)

Here is the same query, but in YAML format: 以下は同じ問い合わせを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 format is left as an exercise for the reader. 読者への演習としてXML形式については記載しません。

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 <command>EXPLAIN EXECUTE</command> to display the execution plan for a prepared query: 以下は、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)

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 <productname>PostgreSQL</productname> releases due to planner improvements. In addition, the <command>ANALYZE</command> command uses random sampling to estimate data statistics; therefore, it is possible for cost estimates to change after a fresh run of <command>ANALYZE</command>, even if the actual distribution of data in the table has not changed. もちろん、ここで示した具体的な数値は対象とするテーブルの実際の中身によって変わります。 また、この数値や選択された問い合わせ戦略は、プランナの改良のため、PostgreSQLのリリース間で異なる可能性がありますので注意してください。 さらに、ANALYZEコマンドは、データの統計情報を推定する際にランダムなサンプリングを行うため、実際のテーブル内の分布が変わっていなくても、新たにANALYZEを実行すると推定コストが変わることがあります。

Notice that the previous example showed a <quote>custom</quote> plan for the specific parameter values given in <command>EXECUTE</command>. We might also wish to see the generic plan for a parameterized query, which can be done with <literal>GENERIC_PLAN</literal>: 前の例では、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)

In this case the parser correctly inferred that <literal>$1</literal> and <literal>$2</literal> should have the same data type as <literal>id</literal>, so the lack of parameter type information from <command>PREPARE</command> 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: この場合では、パーサは$1$2idと同じデータ型を持つべきだと正しく推測していたので、PREPAREからのパラメータ型情報の欠如は問題ではありませんでした。 他の場合には、パラメータ記号の型を明示的に指定することが必要かもしれません。これは、例えば以下のように、それらをキャストすることによって可能です。

EXPLAIN (GENERIC_PLAN)
  SELECT sum(bar) FROM test
    WHERE id > $1::integer AND id < $2::integer
    GROUP BY foo;

互換性

<title>Compatibility</title>

There is no <command>EXPLAIN</command> statement defined in the SQL standard. 標準SQLではEXPLAIN文は定義されていません。

関連項目

<title>See Also</title> ANALYZE