gooderp18绿色标准版
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

763 行
46KB

  1. <?xml version="1.0" encoding="UTF-8" standalone="no"?>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>14.1. Using EXPLAIN</title><link rel="stylesheet" type="text/css" href="stylesheet.css" /><link rev="made" href="pgsql-docs@lists.postgresql.org" /><meta name="generator" content="DocBook XSL Stylesheets V1.79.1" /><link rel="prev" href="performance-tips.html" title="Chapter 14. Performance Tips" /><link rel="next" href="planner-stats.html" title="14.2. Statistics Used by the Planner" /></head><body><div xmlns="http://www.w3.org/TR/xhtml1/transitional" class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="5" align="center">14.1. Using <code xmlns="http://www.w3.org/1999/xhtml" class="command">EXPLAIN</code></th></tr><tr><td width="10%" align="left"><a accesskey="p" href="performance-tips.html" title="Chapter 14. Performance Tips">Prev</a> </td><td width="10%" align="left"><a accesskey="u" href="performance-tips.html" title="Chapter 14. Performance Tips">Up</a></td><th width="60%" align="center">Chapter 14. Performance Tips</th><td width="10%" align="right"><a accesskey="h" href="index.html" title="PostgreSQL 12.4 Documentation">Home</a></td><td width="10%" align="right"> <a accesskey="n" href="planner-stats.html" title="14.2. Statistics Used by the Planner">Next</a></td></tr></table><hr></hr></div><div class="sect1" id="USING-EXPLAIN"><div class="titlepage"><div><div><h2 class="title" style="clear: both">14.1. Using <code class="command">EXPLAIN</code></h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="sect2"><a href="using-explain.html#USING-EXPLAIN-BASICS">14.1.1. <code class="command">EXPLAIN</code> Basics</a></span></dt><dt><span class="sect2"><a href="using-explain.html#USING-EXPLAIN-ANALYZE">14.1.2. <code class="command">EXPLAIN ANALYZE</code></a></span></dt><dt><span class="sect2"><a href="using-explain.html#USING-EXPLAIN-CAVEATS">14.1.3. Caveats</a></span></dt></dl></div><a id="id-1.5.13.4.2" class="indexterm"></a><a id="id-1.5.13.4.3" class="indexterm"></a><p>
  3. <span class="productname">PostgreSQL</span> devises a <em class="firstterm">query
  4. plan</em> for each query it receives. Choosing the right
  5. plan to match the query structure and the properties of the data
  6. is absolutely critical for good performance, so the system includes
  7. a complex <em class="firstterm">planner</em> that tries to choose good plans.
  8. You can use the <a class="xref" href="sql-explain.html" title="EXPLAIN"><span class="refentrytitle">EXPLAIN</span></a> command
  9. to see what query plan the planner creates for any query.
  10. Plan-reading is an art that requires some experience to master,
  11. but this section attempts to cover the basics.
  12. </p><p>
  13. Examples in this section are drawn from the regression test database
  14. after doing a <code class="command">VACUUM ANALYZE</code>, using 9.3 development sources.
  15. You should be able to get similar results if you try the examples
  16. yourself, but your estimated costs and row counts might vary slightly
  17. because <code class="command">ANALYZE</code>'s statistics are random samples rather
  18. than exact, and because costs are inherently somewhat platform-dependent.
  19. </p><p>
  20. The examples use <code class="command">EXPLAIN</code>'s default <span class="quote">“<span class="quote">text</span>”</span> output
  21. format, which is compact and convenient for humans to read.
  22. If you want to feed <code class="command">EXPLAIN</code>'s output to a program for further
  23. analysis, you should use one of its machine-readable output formats
  24. (XML, JSON, or YAML) instead.
  25. </p><div class="sect2" id="USING-EXPLAIN-BASICS"><div class="titlepage"><div><div><h3 class="title">14.1.1. <code class="command">EXPLAIN</code> Basics</h3></div></div></div><p>
  26. The structure of a query plan is a tree of <em class="firstterm">plan nodes</em>.
  27. Nodes at the bottom level of the tree are scan nodes: they return raw rows
  28. from a table. There are different types of scan nodes for different
  29. table access methods: sequential scans, index scans, and bitmap index
  30. scans. There are also non-table row sources, such as <code class="literal">VALUES</code>
  31. clauses and set-returning functions in <code class="literal">FROM</code>, which have their
  32. own scan node types.
  33. If the query requires joining, aggregation, sorting, or other
  34. operations on the raw rows, then there will be additional nodes
  35. above the scan nodes to perform these operations. Again,
  36. there is usually more than one possible way to do these operations,
  37. so different node types can appear here too. The output
  38. of <code class="command">EXPLAIN</code> has one line for each node in the plan
  39. tree, showing the basic node type plus the cost estimates that the planner
  40. made for the execution of that plan node. Additional lines might appear,
  41. indented from the node's summary line,
  42. to show additional properties of the node.
  43. The very first line (the summary line for the topmost
  44. node) has the estimated total execution cost for the plan; it is this
  45. number that the planner seeks to minimize.
  46. </p><p>
  47. Here is a trivial example, just to show what the output looks like:
  48. </p><pre class="screen">
  49. EXPLAIN SELECT * FROM tenk1;
  50. QUERY PLAN
  51. -------------------------------------------------------------
  52. Seq Scan on tenk1 (cost=0.00..458.00 rows=10000 width=244)
  53. </pre><p>
  54. </p><p>
  55. Since this query has no <code class="literal">WHERE</code> clause, it must scan all the
  56. rows of the table, so the planner has chosen to use a simple sequential
  57. scan plan. The numbers that are quoted in parentheses are (left
  58. to right):
  59. </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
  60. Estimated start-up cost. This is the time expended before the output
  61. phase can begin, e.g., time to do the sorting in a sort node.
  62. </p></li><li class="listitem"><p>
  63. Estimated total cost. This is stated on the assumption that the plan
  64. node is run to completion, i.e., all available rows are retrieved.
  65. In practice a node's parent node might stop short of reading all
  66. available rows (see the <code class="literal">LIMIT</code> example below).
  67. </p></li><li class="listitem"><p>
  68. Estimated number of rows output by this plan node. Again, the node
  69. is assumed to be run to completion.
  70. </p></li><li class="listitem"><p>
  71. Estimated average width of rows output by this plan node (in bytes).
  72. </p></li></ul></div><p>
  73. </p><p>
  74. The costs are measured in arbitrary units determined by the planner's
  75. cost parameters (see <a class="xref" href="runtime-config-query.html#RUNTIME-CONFIG-QUERY-CONSTANTS" title="19.7.2. Planner Cost Constants">Section 19.7.2</a>).
  76. Traditional practice is to measure the costs in units of disk page
  77. fetches; that is, <a class="xref" href="runtime-config-query.html#GUC-SEQ-PAGE-COST">seq_page_cost</a> is conventionally
  78. set to <code class="literal">1.0</code> and the other cost parameters are set relative
  79. to that. The examples in this section are run with the default cost
  80. parameters.
  81. </p><p>
  82. It's important to understand that the cost of an upper-level node includes
  83. the cost of all its child nodes. It's also important to realize that
  84. the cost only reflects things that the planner cares about.
  85. In particular, the cost does not consider the time spent transmitting
  86. result rows to the client, which could be an important
  87. factor in the real elapsed time; but the planner ignores it because
  88. it cannot change it by altering the plan. (Every correct plan will
  89. output the same row set, we trust.)
  90. </p><p>
  91. The <code class="literal">rows</code> value is a little tricky because it is
  92. not the number of rows processed or scanned by the
  93. plan node, but rather the number emitted by the node. This is often
  94. less than the number scanned, as a result of filtering by any
  95. <code class="literal">WHERE</code>-clause conditions that are being applied at the node.
  96. Ideally the top-level rows estimate will approximate the number of rows
  97. actually returned, updated, or deleted by the query.
  98. </p><p>
  99. Returning to our example:
  100. </p><pre class="screen">
  101. EXPLAIN SELECT * FROM tenk1;
  102. QUERY PLAN
  103. -------------------------------------------------------------
  104. Seq Scan on tenk1 (cost=0.00..458.00 rows=10000 width=244)
  105. </pre><p>
  106. </p><p>
  107. These numbers are derived very straightforwardly. If you do:
  108. </p><pre class="programlisting">
  109. SELECT relpages, reltuples FROM pg_class WHERE relname = 'tenk1';
  110. </pre><p>
  111. you will find that <code class="classname">tenk1</code> has 358 disk
  112. pages and 10000 rows. The estimated cost is computed as (disk pages read *
  113. <a class="xref" href="runtime-config-query.html#GUC-SEQ-PAGE-COST">seq_page_cost</a>) + (rows scanned *
  114. <a class="xref" href="runtime-config-query.html#GUC-CPU-TUPLE-COST">cpu_tuple_cost</a>). By default,
  115. <code class="varname">seq_page_cost</code> is 1.0 and <code class="varname">cpu_tuple_cost</code> is 0.01,
  116. so the estimated cost is (358 * 1.0) + (10000 * 0.01) = 458.
  117. </p><p>
  118. Now let's modify the query to add a <code class="literal">WHERE</code> condition:
  119. </p><pre class="screen">
  120. EXPLAIN SELECT * FROM tenk1 WHERE unique1 &lt; 7000;
  121. QUERY PLAN
  122. ------------------------------------------------------------
  123. Seq Scan on tenk1 (cost=0.00..483.00 rows=7001 width=244)
  124. Filter: (unique1 &lt; 7000)
  125. </pre><p>
  126. Notice that the <code class="command">EXPLAIN</code> output shows the <code class="literal">WHERE</code>
  127. clause being applied as a <span class="quote">“<span class="quote">filter</span>”</span> condition attached to the Seq
  128. Scan plan node. This means that
  129. the plan node checks the condition for each row it scans, and outputs
  130. only the ones that pass the condition.
  131. The estimate of output rows has been reduced because of the
  132. <code class="literal">WHERE</code> clause.
  133. However, the scan will still have to visit all 10000 rows, so the cost
  134. hasn't decreased; in fact it has gone up a bit (by 10000 * <a class="xref" href="runtime-config-query.html#GUC-CPU-OPERATOR-COST">cpu_operator_cost</a>, to be exact) to reflect the extra CPU
  135. time spent checking the <code class="literal">WHERE</code> condition.
  136. </p><p>
  137. The actual number of rows this query would select is 7000, but the <code class="literal">rows</code>
  138. estimate is only approximate. If you try to duplicate this experiment,
  139. you will probably get a slightly different estimate; moreover, it can
  140. change after each <code class="command">ANALYZE</code> command, because the
  141. statistics produced by <code class="command">ANALYZE</code> are taken from a
  142. randomized sample of the table.
  143. </p><p>
  144. Now, let's make the condition more restrictive:
  145. </p><pre class="screen">
  146. EXPLAIN SELECT * FROM tenk1 WHERE unique1 &lt; 100;
  147. QUERY PLAN
  148. ------------------------------------------------------------------------------
  149. Bitmap Heap Scan on tenk1 (cost=5.07..229.20 rows=101 width=244)
  150. Recheck Cond: (unique1 &lt; 100)
  151. -&gt; Bitmap Index Scan on tenk1_unique1 (cost=0.00..5.04 rows=101 width=0)
  152. Index Cond: (unique1 &lt; 100)
  153. </pre><p>
  154. Here the planner has decided to use a two-step plan: the child plan
  155. node visits an index to find the locations of rows matching the index
  156. condition, and then the upper plan node actually fetches those rows
  157. from the table itself. Fetching rows separately is much more
  158. expensive than reading them sequentially, but because not all the pages
  159. of the table have to be visited, this is still cheaper than a sequential
  160. scan. (The reason for using two plan levels is that the upper plan
  161. node sorts the row locations identified by the index into physical order
  162. before reading them, to minimize the cost of separate fetches.
  163. The <span class="quote">“<span class="quote">bitmap</span>”</span> mentioned in the node names is the mechanism that
  164. does the sorting.)
  165. </p><p>
  166. Now let's add another condition to the <code class="literal">WHERE</code> clause:
  167. </p><pre class="screen">
  168. EXPLAIN SELECT * FROM tenk1 WHERE unique1 &lt; 100 AND stringu1 = 'xxx';
  169. QUERY PLAN
  170. ------------------------------------------------------------------------------
  171. Bitmap Heap Scan on tenk1 (cost=5.04..229.43 rows=1 width=244)
  172. Recheck Cond: (unique1 &lt; 100)
  173. Filter: (stringu1 = 'xxx'::name)
  174. -&gt; Bitmap Index Scan on tenk1_unique1 (cost=0.00..5.04 rows=101 width=0)
  175. Index Cond: (unique1 &lt; 100)
  176. </pre><p>
  177. The added condition <code class="literal">stringu1 = 'xxx'</code> reduces the
  178. output row count estimate, but not the cost because we still have to visit
  179. the same set of rows. Notice that the <code class="literal">stringu1</code> clause
  180. cannot be applied as an index condition, since this index is only on
  181. the <code class="literal">unique1</code> column. Instead it is applied as a filter on
  182. the rows retrieved by the index. Thus the cost has actually gone up
  183. slightly to reflect this extra checking.
  184. </p><p>
  185. In some cases the planner will prefer a <span class="quote">“<span class="quote">simple</span>”</span> index scan plan:
  186. </p><pre class="screen">
  187. EXPLAIN SELECT * FROM tenk1 WHERE unique1 = 42;
  188. QUERY PLAN
  189. -----------------------------------------------------------------------------
  190. Index Scan using tenk1_unique1 on tenk1 (cost=0.29..8.30 rows=1 width=244)
  191. Index Cond: (unique1 = 42)
  192. </pre><p>
  193. In this type of plan the table rows are fetched in index order, which
  194. makes them even more expensive to read, but there are so few that the
  195. extra cost of sorting the row locations is not worth it. You'll most
  196. often see this plan type for queries that fetch just a single row. It's
  197. also often used for queries that have an <code class="literal">ORDER BY</code> condition
  198. that matches the index order, because then no extra sorting step is needed
  199. to satisfy the <code class="literal">ORDER BY</code>.
  200. </p><p>
  201. If there are separate indexes on several of the columns referenced
  202. in <code class="literal">WHERE</code>, the planner might choose to use an AND or OR
  203. combination of the indexes:
  204. </p><pre class="screen">
  205. EXPLAIN SELECT * FROM tenk1 WHERE unique1 &lt; 100 AND unique2 &gt; 9000;
  206. QUERY PLAN
  207. -------------------------------------------------------------------------------------
  208. Bitmap Heap Scan on tenk1 (cost=25.08..60.21 rows=10 width=244)
  209. Recheck Cond: ((unique1 &lt; 100) AND (unique2 &gt; 9000))
  210. -&gt; BitmapAnd (cost=25.08..25.08 rows=10 width=0)
  211. -&gt; Bitmap Index Scan on tenk1_unique1 (cost=0.00..5.04 rows=101 width=0)
  212. Index Cond: (unique1 &lt; 100)
  213. -&gt; Bitmap Index Scan on tenk1_unique2 (cost=0.00..19.78 rows=999 width=0)
  214. Index Cond: (unique2 &gt; 9000)
  215. </pre><p>
  216. But this requires visiting both indexes, so it's not necessarily a win
  217. compared to using just one index and treating the other condition as
  218. a filter. If you vary the ranges involved you'll see the plan change
  219. accordingly.
  220. </p><p>
  221. Here is an example showing the effects of <code class="literal">LIMIT</code>:
  222. </p><pre class="screen">
  223. EXPLAIN SELECT * FROM tenk1 WHERE unique1 &lt; 100 AND unique2 &gt; 9000 LIMIT 2;
  224. QUERY PLAN
  225. -------------------------------------------------------------------------------------
  226. Limit (cost=0.29..14.48 rows=2 width=244)
  227. -&gt; Index Scan using tenk1_unique2 on tenk1 (cost=0.29..71.27 rows=10 width=244)
  228. Index Cond: (unique2 &gt; 9000)
  229. Filter: (unique1 &lt; 100)
  230. </pre><p>
  231. </p><p>
  232. This is the same query as above, but we added a <code class="literal">LIMIT</code> so that
  233. not all the rows need be retrieved, and the planner changed its mind about
  234. what to do. Notice that the total cost and row count of the Index Scan
  235. node are shown as if it were run to completion. However, the Limit node
  236. is expected to stop after retrieving only a fifth of those rows, so its
  237. total cost is only a fifth as much, and that's the actual estimated cost
  238. of the query. This plan is preferred over adding a Limit node to the
  239. previous plan because the Limit could not avoid paying the startup cost
  240. of the bitmap scan, so the total cost would be something over 25 units
  241. with that approach.
  242. </p><p>
  243. Let's try joining two tables, using the columns we have been discussing:
  244. </p><pre class="screen">
  245. EXPLAIN SELECT *
  246. FROM tenk1 t1, tenk2 t2
  247. WHERE t1.unique1 &lt; 10 AND t1.unique2 = t2.unique2;
  248. QUERY PLAN
  249. --------------------------------------------------------------------------------------
  250. Nested Loop (cost=4.65..118.62 rows=10 width=488)
  251. -&gt; Bitmap Heap Scan on tenk1 t1 (cost=4.36..39.47 rows=10 width=244)
  252. Recheck Cond: (unique1 &lt; 10)
  253. -&gt; Bitmap Index Scan on tenk1_unique1 (cost=0.00..4.36 rows=10 width=0)
  254. Index Cond: (unique1 &lt; 10)
  255. -&gt; Index Scan using tenk2_unique2 on tenk2 t2 (cost=0.29..7.91 rows=1 width=244)
  256. Index Cond: (unique2 = t1.unique2)
  257. </pre><p>
  258. </p><p>
  259. In this plan, we have a nested-loop join node with two table scans as
  260. inputs, or children. The indentation of the node summary lines reflects
  261. the plan tree structure. The join's first, or <span class="quote">“<span class="quote">outer</span>”</span>, child
  262. is a bitmap scan similar to those we saw before. Its cost and row count
  263. are the same as we'd get from <code class="literal">SELECT ... WHERE unique1 &lt; 10</code>
  264. because we are
  265. applying the <code class="literal">WHERE</code> clause <code class="literal">unique1 &lt; 10</code>
  266. at that node.
  267. The <code class="literal">t1.unique2 = t2.unique2</code> clause is not relevant yet,
  268. so it doesn't affect the row count of the outer scan. The nested-loop
  269. join node will run its second,
  270. or <span class="quote">“<span class="quote">inner</span>”</span> child once for each row obtained from the outer child.
  271. Column values from the current outer row can be plugged into the inner
  272. scan; here, the <code class="literal">t1.unique2</code> value from the outer row is available,
  273. so we get a plan and costs similar to what we saw above for a simple
  274. <code class="literal">SELECT ... WHERE t2.unique2 = <em class="replaceable"><code>constant</code></em></code> case.
  275. (The estimated cost is actually a bit lower than what was seen above,
  276. as a result of caching that's expected to occur during the repeated
  277. index scans on <code class="literal">t2</code>.) The
  278. costs of the loop node are then set on the basis of the cost of the outer
  279. scan, plus one repetition of the inner scan for each outer row (10 * 7.91,
  280. here), plus a little CPU time for join processing.
  281. </p><p>
  282. In this example the join's output row count is the same as the product
  283. of the two scans' row counts, but that's not true in all cases because
  284. there can be additional <code class="literal">WHERE</code> clauses that mention both tables
  285. and so can only be applied at the join point, not to either input scan.
  286. Here's an example:
  287. </p><pre class="screen">
  288. EXPLAIN SELECT *
  289. FROM tenk1 t1, tenk2 t2
  290. WHERE t1.unique1 &lt; 10 AND t2.unique2 &lt; 10 AND t1.hundred &lt; t2.hundred;
  291. QUERY PLAN
  292. ---------------------------------------------------------------------------------------------
  293. Nested Loop (cost=4.65..49.46 rows=33 width=488)
  294. Join Filter: (t1.hundred &lt; t2.hundred)
  295. -&gt; Bitmap Heap Scan on tenk1 t1 (cost=4.36..39.47 rows=10 width=244)
  296. Recheck Cond: (unique1 &lt; 10)
  297. -&gt; Bitmap Index Scan on tenk1_unique1 (cost=0.00..4.36 rows=10 width=0)
  298. Index Cond: (unique1 &lt; 10)
  299. -&gt; Materialize (cost=0.29..8.51 rows=10 width=244)
  300. -&gt; Index Scan using tenk2_unique2 on tenk2 t2 (cost=0.29..8.46 rows=10 width=244)
  301. Index Cond: (unique2 &lt; 10)
  302. </pre><p>
  303. The condition <code class="literal">t1.hundred &lt; t2.hundred</code> can't be
  304. tested in the <code class="literal">tenk2_unique2</code> index, so it's applied at the
  305. join node. This reduces the estimated output row count of the join node,
  306. but does not change either input scan.
  307. </p><p>
  308. Notice that here the planner has chosen to <span class="quote">“<span class="quote">materialize</span>”</span> the inner
  309. relation of the join, by putting a Materialize plan node atop it. This
  310. means that the <code class="literal">t2</code> index scan will be done just once, even
  311. though the nested-loop join node needs to read that data ten times, once
  312. for each row from the outer relation. The Materialize node saves the data
  313. in memory as it's read, and then returns the data from memory on each
  314. subsequent pass.
  315. </p><p>
  316. When dealing with outer joins, you might see join plan nodes with both
  317. <span class="quote">“<span class="quote">Join Filter</span>”</span> and plain <span class="quote">“<span class="quote">Filter</span>”</span> conditions attached.
  318. Join Filter conditions come from the outer join's <code class="literal">ON</code> clause,
  319. so a row that fails the Join Filter condition could still get emitted as
  320. a null-extended row. But a plain Filter condition is applied after the
  321. outer-join rules and so acts to remove rows unconditionally. In an inner
  322. join there is no semantic difference between these types of filters.
  323. </p><p>
  324. If we change the query's selectivity a bit, we might get a very different
  325. join plan:
  326. </p><pre class="screen">
  327. EXPLAIN SELECT *
  328. FROM tenk1 t1, tenk2 t2
  329. WHERE t1.unique1 &lt; 100 AND t1.unique2 = t2.unique2;
  330. QUERY PLAN
  331. ------------------------------------------------------------------------------------------
  332. Hash Join (cost=230.47..713.98 rows=101 width=488)
  333. Hash Cond: (t2.unique2 = t1.unique2)
  334. -&gt; Seq Scan on tenk2 t2 (cost=0.00..445.00 rows=10000 width=244)
  335. -&gt; Hash (cost=229.20..229.20 rows=101 width=244)
  336. -&gt; Bitmap Heap Scan on tenk1 t1 (cost=5.07..229.20 rows=101 width=244)
  337. Recheck Cond: (unique1 &lt; 100)
  338. -&gt; Bitmap Index Scan on tenk1_unique1 (cost=0.00..5.04 rows=101 width=0)
  339. Index Cond: (unique1 &lt; 100)
  340. </pre><p>
  341. </p><p>
  342. Here, the planner has chosen to use a hash join, in which rows of one
  343. table are entered into an in-memory hash table, after which the other
  344. table is scanned and the hash table is probed for matches to each row.
  345. Again note how the indentation reflects the plan structure: the bitmap
  346. scan on <code class="literal">tenk1</code> is the input to the Hash node, which constructs
  347. the hash table. That's then returned to the Hash Join node, which reads
  348. rows from its outer child plan and searches the hash table for each one.
  349. </p><p>
  350. Another possible type of join is a merge join, illustrated here:
  351. </p><pre class="screen">
  352. EXPLAIN SELECT *
  353. FROM tenk1 t1, onek t2
  354. WHERE t1.unique1 &lt; 100 AND t1.unique2 = t2.unique2;
  355. QUERY PLAN
  356. ------------------------------------------------------------------------------------------
  357. Merge Join (cost=198.11..268.19 rows=10 width=488)
  358. Merge Cond: (t1.unique2 = t2.unique2)
  359. -&gt; Index Scan using tenk1_unique2 on tenk1 t1 (cost=0.29..656.28 rows=101 width=244)
  360. Filter: (unique1 &lt; 100)
  361. -&gt; Sort (cost=197.83..200.33 rows=1000 width=244)
  362. Sort Key: t2.unique2
  363. -&gt; Seq Scan on onek t2 (cost=0.00..148.00 rows=1000 width=244)
  364. </pre><p>
  365. </p><p>
  366. Merge join requires its input data to be sorted on the join keys. In this
  367. plan the <code class="literal">tenk1</code> data is sorted by using an index scan to visit
  368. the rows in the correct order, but a sequential scan and sort is preferred
  369. for <code class="literal">onek</code>, because there are many more rows to be visited in
  370. that table.
  371. (Sequential-scan-and-sort frequently beats an index scan for sorting many rows,
  372. because of the nonsequential disk access required by the index scan.)
  373. </p><p>
  374. One way to look at variant plans is to force the planner to disregard
  375. whatever strategy it thought was the cheapest, using the enable/disable
  376. flags described in <a class="xref" href="runtime-config-query.html#RUNTIME-CONFIG-QUERY-ENABLE" title="19.7.1. Planner Method Configuration">Section 19.7.1</a>.
  377. (This is a crude tool, but useful. See
  378. also <a class="xref" href="explicit-joins.html" title="14.3. Controlling the Planner with Explicit JOIN Clauses">Section 14.3</a>.)
  379. For example, if we're unconvinced that sequential-scan-and-sort is the best way to
  380. deal with table <code class="literal">onek</code> in the previous example, we could try
  381. </p><pre class="screen">
  382. SET enable_sort = off;
  383. EXPLAIN SELECT *
  384. FROM tenk1 t1, onek t2
  385. WHERE t1.unique1 &lt; 100 AND t1.unique2 = t2.unique2;
  386. QUERY PLAN
  387. ------------------------------------------------------------------------------------------
  388. Merge Join (cost=0.56..292.65 rows=10 width=488)
  389. Merge Cond: (t1.unique2 = t2.unique2)
  390. -&gt; Index Scan using tenk1_unique2 on tenk1 t1 (cost=0.29..656.28 rows=101 width=244)
  391. Filter: (unique1 &lt; 100)
  392. -&gt; Index Scan using onek_unique2 on onek t2 (cost=0.28..224.79 rows=1000 width=244)
  393. </pre><p>
  394. which shows that the planner thinks that sorting <code class="literal">onek</code> by
  395. index-scanning is about 12% more expensive than sequential-scan-and-sort.
  396. Of course, the next question is whether it's right about that.
  397. We can investigate that using <code class="command">EXPLAIN ANALYZE</code>, as discussed
  398. below.
  399. </p></div><div class="sect2" id="USING-EXPLAIN-ANALYZE"><div class="titlepage"><div><div><h3 class="title">14.1.2. <code class="command">EXPLAIN ANALYZE</code></h3></div></div></div><p>
  400. It is possible to check the accuracy of the planner's estimates
  401. by using <code class="command">EXPLAIN</code>'s <code class="literal">ANALYZE</code> option. With this
  402. option, <code class="command">EXPLAIN</code> actually executes the query, and then displays
  403. the true row counts and true run time accumulated within each plan node,
  404. along with the same estimates that a plain <code class="command">EXPLAIN</code>
  405. shows. For example, we might get a result like this:
  406. </p><pre class="screen">
  407. EXPLAIN ANALYZE SELECT *
  408. FROM tenk1 t1, tenk2 t2
  409. WHERE t1.unique1 &lt; 10 AND t1.unique2 = t2.unique2;
  410. QUERY PLAN
  411. ---------------------------------------------------------------------------------------------------------------------------------
  412. Nested Loop (cost=4.65..118.62 rows=10 width=488) (actual time=0.128..0.377 rows=10 loops=1)
  413. -&gt; Bitmap Heap Scan on tenk1 t1 (cost=4.36..39.47 rows=10 width=244) (actual time=0.057..0.121 rows=10 loops=1)
  414. Recheck Cond: (unique1 &lt; 10)
  415. -&gt; Bitmap Index Scan on tenk1_unique1 (cost=0.00..4.36 rows=10 width=0) (actual time=0.024..0.024 rows=10 loops=1)
  416. Index Cond: (unique1 &lt; 10)
  417. -&gt; Index Scan using tenk2_unique2 on tenk2 t2 (cost=0.29..7.91 rows=1 width=244) (actual time=0.021..0.022 rows=1 loops=10)
  418. Index Cond: (unique2 = t1.unique2)
  419. Planning time: 0.181 ms
  420. Execution time: 0.501 ms
  421. </pre><p>
  422. Note that the <span class="quote">“<span class="quote">actual time</span>”</span> values are in milliseconds of
  423. real time, whereas the <code class="literal">cost</code> estimates are expressed in
  424. arbitrary units; so they are unlikely to match up.
  425. The thing that's usually most important to look for is whether the
  426. estimated row counts are reasonably close to reality. In this example
  427. the estimates were all dead-on, but that's quite unusual in practice.
  428. </p><p>
  429. In some query plans, it is possible for a subplan node to be executed more
  430. than once. For example, the inner index scan will be executed once per
  431. outer row in the above nested-loop plan. In such cases, the
  432. <code class="literal">loops</code> value reports the
  433. total number of executions of the node, and the actual time and rows
  434. values shown are averages per-execution. This is done to make the numbers
  435. comparable with the way that the cost estimates are shown. Multiply by
  436. the <code class="literal">loops</code> value to get the total time actually spent in
  437. the node. In the above example, we spent a total of 0.220 milliseconds
  438. executing the index scans on <code class="literal">tenk2</code>.
  439. </p><p>
  440. In some cases <code class="command">EXPLAIN ANALYZE</code> shows additional execution
  441. statistics beyond the plan node execution times and row counts.
  442. For example, Sort and Hash nodes provide extra information:
  443. </p><pre class="screen">
  444. EXPLAIN ANALYZE SELECT *
  445. FROM tenk1 t1, tenk2 t2
  446. WHERE t1.unique1 &lt; 100 AND t1.unique2 = t2.unique2 ORDER BY t1.fivethous;
  447. QUERY PLAN
  448. --------------------------------------------------------------------------------------------------------------------------------------------
  449. Sort (cost=717.34..717.59 rows=101 width=488) (actual time=7.761..7.774 rows=100 loops=1)
  450. Sort Key: t1.fivethous
  451. Sort Method: quicksort Memory: 77kB
  452. -&gt; Hash Join (cost=230.47..713.98 rows=101 width=488) (actual time=0.711..7.427 rows=100 loops=1)
  453. Hash Cond: (t2.unique2 = t1.unique2)
  454. -&gt; Seq Scan on tenk2 t2 (cost=0.00..445.00 rows=10000 width=244) (actual time=0.007..2.583 rows=10000 loops=1)
  455. -&gt; Hash (cost=229.20..229.20 rows=101 width=244) (actual time=0.659..0.659 rows=100 loops=1)
  456. Buckets: 1024 Batches: 1 Memory Usage: 28kB
  457. -&gt; Bitmap Heap Scan on tenk1 t1 (cost=5.07..229.20 rows=101 width=244) (actual time=0.080..0.526 rows=100 loops=1)
  458. Recheck Cond: (unique1 &lt; 100)
  459. -&gt; Bitmap Index Scan on tenk1_unique1 (cost=0.00..5.04 rows=101 width=0) (actual time=0.049..0.049 rows=100 loops=1)
  460. Index Cond: (unique1 &lt; 100)
  461. Planning time: 0.194 ms
  462. Execution time: 8.008 ms
  463. </pre><p>
  464. The Sort node shows the sort method used (in particular, whether the sort
  465. was in-memory or on-disk) and the amount of memory or disk space needed.
  466. The Hash node shows the number of hash buckets and batches as well as the
  467. peak amount of memory used for the hash table. (If the number of batches
  468. exceeds one, there will also be disk space usage involved, but that is not
  469. shown.)
  470. </p><p>
  471. Another type of extra information is the number of rows removed by a
  472. filter condition:
  473. </p><pre class="screen">
  474. EXPLAIN ANALYZE SELECT * FROM tenk1 WHERE ten &lt; 7;
  475. QUERY PLAN
  476. ---------------------------------------------------------------------------------------------------------
  477. Seq Scan on tenk1 (cost=0.00..483.00 rows=7000 width=244) (actual time=0.016..5.107 rows=7000 loops=1)
  478. Filter: (ten &lt; 7)
  479. Rows Removed by Filter: 3000
  480. Planning time: 0.083 ms
  481. Execution time: 5.905 ms
  482. </pre><p>
  483. These counts can be particularly valuable for filter conditions applied at
  484. join nodes. The <span class="quote">“<span class="quote">Rows Removed</span>”</span> line only appears when at least
  485. one scanned row, or potential join pair in the case of a join node,
  486. is rejected by the filter condition.
  487. </p><p>
  488. A case similar to filter conditions occurs with <span class="quote">“<span class="quote">lossy</span>”</span>
  489. index scans. For example, consider this search for polygons containing a
  490. specific point:
  491. </p><pre class="screen">
  492. EXPLAIN ANALYZE SELECT * FROM polygon_tbl WHERE f1 @&gt; polygon '(0.5,2.0)';
  493. QUERY PLAN
  494. ------------------------------------------------------------------------------------------------------
  495. Seq Scan on polygon_tbl (cost=0.00..1.05 rows=1 width=32) (actual time=0.044..0.044 rows=0 loops=1)
  496. Filter: (f1 @&gt; '((0.5,2))'::polygon)
  497. Rows Removed by Filter: 4
  498. Planning time: 0.040 ms
  499. Execution time: 0.083 ms
  500. </pre><p>
  501. The planner thinks (quite correctly) that this sample table is too small
  502. to bother with an index scan, so we have a plain sequential scan in which
  503. all the rows got rejected by the filter condition. But if we force an
  504. index scan to be used, we see:
  505. </p><pre class="screen">
  506. SET enable_seqscan TO off;
  507. EXPLAIN ANALYZE SELECT * FROM polygon_tbl WHERE f1 @&gt; polygon '(0.5,2.0)';
  508. QUERY PLAN
  509. --------------------------------------------------------------------------------------------------------------------------
  510. Index Scan using gpolygonind on polygon_tbl (cost=0.13..8.15 rows=1 width=32) (actual time=0.062..0.062 rows=0 loops=1)
  511. Index Cond: (f1 @&gt; '((0.5,2))'::polygon)
  512. Rows Removed by Index Recheck: 1
  513. Planning time: 0.034 ms
  514. Execution time: 0.144 ms
  515. </pre><p>
  516. Here we can see that the index returned one candidate row, which was
  517. then rejected by a recheck of the index condition. This happens because a
  518. GiST index is <span class="quote">“<span class="quote">lossy</span>”</span> for polygon containment tests: it actually
  519. returns the rows with polygons that overlap the target, and then we have
  520. to do the exact containment test on those rows.
  521. </p><p>
  522. <code class="command">EXPLAIN</code> has a <code class="literal">BUFFERS</code> option that can be used with
  523. <code class="literal">ANALYZE</code> to get even more run time statistics:
  524. </p><pre class="screen">
  525. EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM tenk1 WHERE unique1 &lt; 100 AND unique2 &gt; 9000;
  526. QUERY PLAN
  527. ---------------------------------------------------------------------------------------------------------------------------------
  528. Bitmap Heap Scan on tenk1 (cost=25.08..60.21 rows=10 width=244) (actual time=0.323..0.342 rows=10 loops=1)
  529. Recheck Cond: ((unique1 &lt; 100) AND (unique2 &gt; 9000))
  530. Buffers: shared hit=15
  531. -&gt; BitmapAnd (cost=25.08..25.08 rows=10 width=0) (actual time=0.309..0.309 rows=0 loops=1)
  532. Buffers: shared hit=7
  533. -&gt; Bitmap Index Scan on tenk1_unique1 (cost=0.00..5.04 rows=101 width=0) (actual time=0.043..0.043 rows=100 loops=1)
  534. Index Cond: (unique1 &lt; 100)
  535. Buffers: shared hit=2
  536. -&gt; Bitmap Index Scan on tenk1_unique2 (cost=0.00..19.78 rows=999 width=0) (actual time=0.227..0.227 rows=999 loops=1)
  537. Index Cond: (unique2 &gt; 9000)
  538. Buffers: shared hit=5
  539. Planning time: 0.088 ms
  540. Execution time: 0.423 ms
  541. </pre><p>
  542. The numbers provided by <code class="literal">BUFFERS</code> help to identify which parts
  543. of the query are the most I/O-intensive.
  544. </p><p>
  545. Keep in mind that because <code class="command">EXPLAIN ANALYZE</code> actually
  546. runs the query, any side-effects will happen as usual, even though
  547. whatever results the query might output are discarded in favor of
  548. printing the <code class="command">EXPLAIN</code> data. If you want to analyze a
  549. data-modifying query without changing your tables, you can
  550. roll the command back afterwards, for example:
  551. </p><pre class="screen">
  552. BEGIN;
  553. EXPLAIN ANALYZE UPDATE tenk1 SET hundred = hundred + 1 WHERE unique1 &lt; 100;
  554. QUERY PLAN
  555. --------------------------------------------------------------------------------------------------------------------------------
  556. Update on tenk1 (cost=5.07..229.46 rows=101 width=250) (actual time=14.628..14.628 rows=0 loops=1)
  557. -&gt; Bitmap Heap Scan on tenk1 (cost=5.07..229.46 rows=101 width=250) (actual time=0.101..0.439 rows=100 loops=1)
  558. Recheck Cond: (unique1 &lt; 100)
  559. -&gt; Bitmap Index Scan on tenk1_unique1 (cost=0.00..5.04 rows=101 width=0) (actual time=0.043..0.043 rows=100 loops=1)
  560. Index Cond: (unique1 &lt; 100)
  561. Planning time: 0.079 ms
  562. Execution time: 14.727 ms
  563. ROLLBACK;
  564. </pre><p>
  565. </p><p>
  566. As seen in this example, when the query is an <code class="command">INSERT</code>,
  567. <code class="command">UPDATE</code>, or <code class="command">DELETE</code> command, the actual work of
  568. applying the table changes is done by a top-level Insert, Update,
  569. or Delete plan node. The plan nodes underneath this node perform
  570. the work of locating the old rows and/or computing the new data.
  571. So above, we see the same sort of bitmap table scan we've seen already,
  572. and its output is fed to an Update node that stores the updated rows.
  573. It's worth noting that although the data-modifying node can take a
  574. considerable amount of run time (here, it's consuming the lion's share
  575. of the time), the planner does not currently add anything to the cost
  576. estimates to account for that work. That's because the work to be done is
  577. the same for every correct query plan, so it doesn't affect planning
  578. decisions.
  579. </p><p>
  580. When an <code class="command">UPDATE</code> or <code class="command">DELETE</code> command affects an
  581. inheritance hierarchy, the output might look like this:
  582. </p><pre class="screen">
  583. EXPLAIN UPDATE parent SET f2 = f2 + 1 WHERE f1 = 101;
  584. QUERY PLAN
  585. -----------------------------------------------------------------------------------
  586. Update on parent (cost=0.00..24.53 rows=4 width=14)
  587. Update on parent
  588. Update on child1
  589. Update on child2
  590. Update on child3
  591. -&gt; Seq Scan on parent (cost=0.00..0.00 rows=1 width=14)
  592. Filter: (f1 = 101)
  593. -&gt; Index Scan using child1_f1_key on child1 (cost=0.15..8.17 rows=1 width=14)
  594. Index Cond: (f1 = 101)
  595. -&gt; Index Scan using child2_f1_key on child2 (cost=0.15..8.17 rows=1 width=14)
  596. Index Cond: (f1 = 101)
  597. -&gt; Index Scan using child3_f1_key on child3 (cost=0.15..8.17 rows=1 width=14)
  598. Index Cond: (f1 = 101)
  599. </pre><p>
  600. In this example the Update node needs to consider three child tables as
  601. well as the originally-mentioned parent table. So there are four input
  602. scanning subplans, one per table. For clarity, the Update node is
  603. annotated to show the specific target tables that will be updated, in the
  604. same order as the corresponding subplans. (These annotations are new as
  605. of <span class="productname">PostgreSQL</span> 9.5; in prior versions the reader had to
  606. intuit the target tables by inspecting the subplans.)
  607. </p><p>
  608. The <code class="literal">Planning time</code> shown by <code class="command">EXPLAIN
  609. ANALYZE</code> is the time it took to generate the query plan from the
  610. parsed query and optimize it. It does not include parsing or rewriting.
  611. </p><p>
  612. The <code class="literal">Execution time</code> shown by <code class="command">EXPLAIN
  613. ANALYZE</code> includes executor start-up and shut-down time, as well
  614. as the time to run any triggers that are fired, but it does not include
  615. parsing, rewriting, or planning time.
  616. Time spent executing <code class="literal">BEFORE</code> triggers, if any, is included in
  617. the time for the related Insert, Update, or Delete node; but time
  618. spent executing <code class="literal">AFTER</code> triggers is not counted there because
  619. <code class="literal">AFTER</code> triggers are fired after completion of the whole plan.
  620. The total time spent in each trigger
  621. (either <code class="literal">BEFORE</code> or <code class="literal">AFTER</code>) is also shown separately.
  622. Note that deferred constraint triggers will not be executed
  623. until end of transaction and are thus not considered at all by
  624. <code class="command">EXPLAIN ANALYZE</code>.
  625. </p></div><div class="sect2" id="USING-EXPLAIN-CAVEATS"><div class="titlepage"><div><div><h3 class="title">14.1.3. Caveats</h3></div></div></div><p>
  626. There are two significant ways in which run times measured by
  627. <code class="command">EXPLAIN ANALYZE</code> can deviate from normal execution of
  628. the same query. First, since no output rows are delivered to the client,
  629. network transmission costs and I/O conversion costs are not included.
  630. Second, the measurement overhead added by <code class="command">EXPLAIN
  631. ANALYZE</code> can be significant, especially on machines with slow
  632. <code class="function">gettimeofday()</code> operating-system calls. You can use the
  633. <a class="xref" href="pgtesttiming.html" title="pg_test_timing"><span class="refentrytitle"><span class="application">pg_test_timing</span></span></a> tool to measure the overhead of timing
  634. on your system.
  635. </p><p>
  636. <code class="command">EXPLAIN</code> results should not be extrapolated to situations
  637. much different from the one you are actually testing; for example,
  638. results on a toy-sized table cannot be assumed to apply to large tables.
  639. The planner's cost estimates are not linear and so it might choose
  640. a different plan for a larger or smaller table. An extreme example
  641. is that on a table that only occupies one disk page, you'll nearly
  642. always get a sequential scan plan whether indexes are available or not.
  643. The planner realizes that it's going to take one disk page read to
  644. process the table in any case, so there's no value in expending additional
  645. page reads to look at an index. (We saw this happening in the
  646. <code class="literal">polygon_tbl</code> example above.)
  647. </p><p>
  648. There are cases in which the actual and estimated values won't match up
  649. well, but nothing is really wrong. One such case occurs when
  650. plan node execution is stopped short by a <code class="literal">LIMIT</code> or similar
  651. effect. For example, in the <code class="literal">LIMIT</code> query we used before,
  652. </p><pre class="screen">
  653. EXPLAIN ANALYZE SELECT * FROM tenk1 WHERE unique1 &lt; 100 AND unique2 &gt; 9000 LIMIT 2;
  654. QUERY PLAN
  655. -------------------------------------------------------------------------------------------------------------------------------
  656. Limit (cost=0.29..14.71 rows=2 width=244) (actual time=0.177..0.249 rows=2 loops=1)
  657. -&gt; Index Scan using tenk1_unique2 on tenk1 (cost=0.29..72.42 rows=10 width=244) (actual time=0.174..0.244 rows=2 loops=1)
  658. Index Cond: (unique2 &gt; 9000)
  659. Filter: (unique1 &lt; 100)
  660. Rows Removed by Filter: 287
  661. Planning time: 0.096 ms
  662. Execution time: 0.336 ms
  663. </pre><p>
  664. the estimated cost and row count for the Index Scan node are shown as
  665. though it were run to completion. But in reality the Limit node stopped
  666. requesting rows after it got two, so the actual row count is only 2 and
  667. the run time is less than the cost estimate would suggest. This is not
  668. an estimation error, only a discrepancy in the way the estimates and true
  669. values are displayed.
  670. </p><p>
  671. Merge joins also have measurement artifacts that can confuse the unwary.
  672. A merge join will stop reading one input if it's exhausted the other input
  673. and the next key value in the one input is greater than the last key value
  674. of the other input; in such a case there can be no more matches and so no
  675. need to scan the rest of the first input. This results in not reading all
  676. of one child, with results like those mentioned for <code class="literal">LIMIT</code>.
  677. Also, if the outer (first) child contains rows with duplicate key values,
  678. the inner (second) child is backed up and rescanned for the portion of its
  679. rows matching that key value. <code class="command">EXPLAIN ANALYZE</code> counts these
  680. repeated emissions of the same inner rows as if they were real additional
  681. rows. When there are many outer duplicates, the reported actual row count
  682. for the inner child plan node can be significantly larger than the number
  683. of rows that are actually in the inner relation.
  684. </p><p>
  685. BitmapAnd and BitmapOr nodes always report their actual row counts as zero,
  686. due to implementation limitations.
  687. </p><p>
  688. Normally, <code class="command">EXPLAIN</code> will display every plan node
  689. created by the planner. However, there are cases where the executor
  690. can determine that certain nodes need not be executed because they
  691. cannot produce any rows, based on parameter values that were not
  692. available at planning time. (Currently this can only happen for child
  693. nodes of an Append or MergeAppend node that is scanning a partitioned
  694. table.) When this happens, those plan nodes are omitted from
  695. the <code class="command">EXPLAIN</code> output and a <code class="literal">Subplans
  696. Removed: <em class="replaceable"><code>N</code></em></code> annotation appears
  697. instead.
  698. </p></div></div><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="performance-tips.html">Prev</a> </td><td width="20%" align="center"><a accesskey="u" href="performance-tips.html">Up</a></td><td width="40%" align="right"> <a accesskey="n" href="planner-stats.html">Next</a></td></tr><tr><td width="40%" align="left" valign="top">Chapter 14. Performance Tips </td><td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td><td width="40%" align="right" valign="top"> 14.2. Statistics Used by the Planner</td></tr></table></div></body></html>
上海开阖软件有限公司 沪ICP备12045867号-1