perform.sgml 33.8 KB
Newer Older
1
<!--
2
$Header: /cvsroot/pgsql/doc/src/sgml/perform.sgml,v 1.26 2003/01/28 03:34:29 momjian Exp $
3 4 5 6 7 8 9 10 11
-->

 <chapter id="performance-tips">
  <title>Performance Tips</title>

  <para>
   Query performance can be affected by many things. Some of these can 
   be manipulated by the user, while others are fundamental to the underlying
   design of the system.  This chapter provides some hints about understanding
12
   and tuning <productname>PostgreSQL</productname> performance.
13 14 15 16 17 18
  </para>

  <sect1 id="using-explain">
   <title>Using <command>EXPLAIN</command></title>

   <para>
19
    <productname>PostgreSQL</productname> devises a <firstterm>query
20 21 22 23
    plan</firstterm> for each query it is given.  Choosing the right
    plan to match the query structure and the properties of the data
    is absolutely critical for good performance.  You can use the
    <command>EXPLAIN</command> command to see what query plan the system
24 25 26
    creates for any query.
    Plan-reading is an art that deserves an extensive tutorial, which
    this is not; but here is some basic information.
27 28 29
   </para>

   <para>
30
    The numbers that are currently quoted by <command>EXPLAIN</command> are:
31 32 33 34

    <itemizedlist>
     <listitem>
      <para>
35 36
       Estimated start-up cost (Time expended before output scan can start,
       e.g., time to do the sorting in a sort node.)
37 38 39 40 41
      </para>
     </listitem>

     <listitem>
      <para>
42 43 44
       Estimated total cost (If all rows are retrieved, which they may not
       be --- a query with a <literal>LIMIT</> clause will stop short of paying the total cost,
       for example.)
45 46 47 48 49
      </para>
     </listitem>

     <listitem>
      <para>
50 51
       Estimated number of rows output by this plan node (Again, only if
       executed to completion.)
52 53 54 55 56 57
      </para>
     </listitem>

     <listitem>
      <para>
       Estimated average width (in bytes) of rows output by this plan
58
       node
59 60 61 62 63 64 65 66
      </para>
     </listitem>
    </itemizedlist>
   </para>

   <para>
    The costs are measured in units of disk page fetches.  (CPU effort
    estimates are converted into disk-page units using some
67
    fairly arbitrary fudge factors. If you want to experiment with these
68
    factors, see the list of run-time configuration parameters in the
69
    &cite-admin;.)
70 71 72 73 74 75 76
   </para>

   <para>
    It's important to note that the cost of an upper-level node includes
    the cost of all its child nodes.  It's also important to realize that
    the cost only reflects things that the planner/optimizer cares about.
    In particular, the cost does not consider the time spent transmitting
77
    result rows to the frontend --- which could be a pretty dominant
78 79
    factor in the true elapsed time, but the planner ignores it because
    it cannot change it by altering the plan.  (Every correct plan will
80
    output the same row set, we trust.)
81 82 83 84 85 86
   </para>

   <para>
    Rows output is a little tricky because it is <emphasis>not</emphasis> the
    number of rows
    processed/scanned by the query --- it is usually less, reflecting the
87
    estimated selectivity of any <literal>WHERE</>-clause constraints that are being
88 89
    applied at this node.  Ideally the top-level rows estimate will
    approximate the number of rows actually returned, updated, or deleted
90
    by the query.
91 92 93 94
   </para>

   <para>
    Here are some examples (using the regress test database after a
95
    <literal>VACUUM ANALYZE</>, and 7.3 development sources):
96

97
<programlisting>
98
regression=# EXPLAIN SELECT * FROM tenk1;
99 100 101
                         QUERY PLAN
-------------------------------------------------------------
 Seq Scan on tenk1  (cost=0.00..333.00 rows=10000 width=148)
102
</programlisting>
103 104 105 106 107
   </para>

   <para>
    This is about as straightforward as it gets.  If you do

108
<programlisting>
109
SELECT * FROM pg_class WHERE relname = 'tenk1';
110
</programlisting>
111

112 113
    you will find out that <classname>tenk1</classname> has 233 disk
    pages and 10000 rows.  So the cost is estimated at 233 page
114 115
    reads, defined as costing 1.0 apiece, plus 10000 * <varname>cpu_tuple_cost</varname> which is
    currently 0.01 (try <command>SHOW cpu_tuple_cost</command>).
116 117 118
   </para>

   <para>
119
    Now let's modify the query to add a <literal>WHERE</> condition:
120

121
<programlisting>
122
regression=# EXPLAIN SELECT * FROM tenk1 WHERE unique1 &lt; 1000;
123 124 125 126
                         QUERY PLAN
------------------------------------------------------------
 Seq Scan on tenk1  (cost=0.00..358.00 rows=1033 width=148)
   Filter: (unique1 &lt; 1000)
127
</programlisting>
128

129
    The estimate of output rows has gone down because of the <literal>WHERE</> clause.
130 131
    However, the scan will still have to visit all 10000 rows, so the cost
    hasn't decreased; in fact it has gone up a bit to reflect the extra CPU
132
    time spent checking the <literal>WHERE</> condition.
133 134 135 136 137 138 139 140 141
   </para>

   <para>
    The actual number of rows this query would select is 1000, but the
    estimate is only approximate.  If you try to duplicate this experiment,
    you will probably get a slightly different estimate; moreover, it will
    change after each <command>ANALYZE</command> command, because the
    statistics produced by <command>ANALYZE</command> are taken from a
    randomized sample of the table.
142 143 144
   </para>

   <para>
145
    Modify the query to restrict the condition even more:
146

147
<programlisting>
148
regression=# EXPLAIN SELECT * FROM tenk1 WHERE unique1 &lt; 50;
149 150 151
                                   QUERY PLAN
-------------------------------------------------------------------------------
 Index Scan using tenk1_unique1 on tenk1  (cost=0.00..179.33 rows=49 width=148)
152
   Index Cond: (unique1 &lt; 50)
153
</programlisting>
154

155
    and you will see that if we make the <literal>WHERE</> condition selective
156
    enough, the planner will
157
    eventually decide that an index scan is cheaper than a sequential scan.
158
    This plan will only have to visit 50 rows because of the index,
159 160
    so it wins despite the fact that each individual fetch is more expensive
    than reading a whole disk page sequentially.
161 162 163
   </para>

   <para>
164
    Add another clause to the <literal>WHERE</> condition:
165

166
<programlisting>
167
regression=# EXPLAIN SELECT * FROM tenk1 WHERE unique1 &lt; 50 AND
168
regression-# stringu1 = 'xxx';
169 170 171
                                  QUERY PLAN
-------------------------------------------------------------------------------
 Index Scan using tenk1_unique1 on tenk1  (cost=0.00..179.45 rows=1 width=148)
172
   Index Cond: (unique1 &lt; 50)
173
   Filter: (stringu1 = 'xxx'::name)
174
</programlisting>
175

176 177
    The added clause <literal>stringu1 = 'xxx'</literal> reduces the
    output-rows estimate, but not the cost because we still have to visit the
178
    same set of rows.  Notice that the <literal>stringu1</> clause
179 180 181 182
    cannot be applied as an index condition (since this index is only on
    the <literal>unique1</> column).  Instead it is applied as a filter on
    the rows retrieved by the index.  Thus the cost has actually gone up
    a little bit to reflect this extra checking.
183 184 185 186 187
   </para>

   <para>
    Let's try joining two tables, using the fields we have been discussing:

188
<programlisting>
189 190
regression=# EXPLAIN SELECT * FROM tenk1 t1, tenk2 t2 WHERE t1.unique1 &lt; 50
regression-# AND t1.unique2 = t2.unique2;
191 192 193 194 195
                               QUERY PLAN
----------------------------------------------------------------------------
 Nested Loop  (cost=0.00..327.02 rows=49 width=296)
   -&gt;  Index Scan using tenk1_unique1 on tenk1 t1
                                      (cost=0.00..179.33 rows=49 width=148)
196
         Index Cond: (unique1 &lt; 50)
197 198
   -&gt;  Index Scan using tenk2_unique2 on tenk2 t2
                                      (cost=0.00..3.01 rows=1 width=148)
199
         Index Cond: ("outer".unique2 = t2.unique2)
200
</programlisting>
201 202 203
   </para>

   <para>
204
    In this nested-loop join, the outer scan is the same index scan we had
205
    in the example before last, and so its cost and row count are the same
206
    because we are applying the <literal>unique1 &lt; 50</literal> <literal>WHERE</> clause at that node.
207
    The <literal>t1.unique2 = t2.unique2</literal> clause is not relevant yet, so it doesn't
208
    affect row count of the outer scan.  For the inner scan, the <literal>unique2</> value of the
209
    current
210
    outer-scan row is plugged into the inner index scan
211
    to produce an index condition like
212
    <literal>t2.unique2 = <replaceable>constant</replaceable></literal>.  So we get the
213 214
     same inner-scan plan and costs that we'd get from, say, <literal>EXPLAIN SELECT
     * FROM tenk2 WHERE unique2 = 42</literal>.  The costs of the loop node are then set
215
     on the basis of the cost of the outer scan, plus one repetition of the
216
     inner scan for each outer row (49 * 3.01, here), plus a little CPU
217 218 219 220 221 222
     time for join processing.
   </para>

   <para>
    In this example the loop's output row count is the same as the product
    of the two scans' row counts, but that's not true in general, because
223
    in general you can have <literal>WHERE</> clauses that mention both relations and
224
    so can only be applied at the join point, not to either input scan.
225
    For example, if we added <literal>WHERE ... AND t1.hundred &lt; t2.hundred</literal>,
226
    that would decrease the output row count of the join node, but not change
227 228 229 230 231 232 233 234 235
    either input scan.
   </para>

   <para>
    One way to look at variant plans is to force the planner to disregard
    whatever strategy it thought was the winner, using the enable/disable
    flags for each plan type.  (This is a crude tool, but useful.  See
    also <xref linkend="explicit-joins">.)

236 237 238
<programlisting>
regression=# SET enable_nestloop = off;
SET
239 240
regression=# EXPLAIN SELECT * FROM tenk1 t1, tenk2 t2 WHERE t1.unique1 &lt; 50
regression-# AND t1.unique2 = t2.unique2;
241 242 243 244 245 246 247 248
                               QUERY PLAN
--------------------------------------------------------------------------
 Hash Join  (cost=179.45..563.06 rows=49 width=296)
   Hash Cond: ("outer".unique2 = "inner".unique2)
   -&gt;  Seq Scan on tenk2 t2  (cost=0.00..333.00 rows=10000 width=148)
   -&gt;  Hash  (cost=179.33..179.33 rows=49 width=148)
         -&gt;  Index Scan using tenk1_unique1 on tenk1 t1
                                    (cost=0.00..179.33 rows=49 width=148)
249
               Index Cond: (unique1 &lt; 50)
250
</programlisting>
251

252 253 254
    This plan proposes to extract the 50 interesting rows of <classname>tenk1</classname>
    using ye same olde index scan, stash them into an in-memory hash table,
    and then do a sequential scan of <classname>tenk2</classname>, probing into the hash table
255
    for possible matches of <literal>t1.unique2 = t2.unique2</literal> at each <classname>tenk2</classname> row.
256
    The cost to read <classname>tenk1</classname> and set up the hash table is entirely start-up
257
    cost for the hash join, since we won't get any rows out until we can
258
    start reading <classname>tenk2</classname>.  The total time estimate for the join also
259 260
    includes a hefty charge for the CPU time to probe the hash table
    10000 times.  Note, however, that we are <emphasis>not</emphasis> charging 10000 times 179.33;
261 262
    the hash table setup is only done once in this plan type.
   </para>
263

264 265
   <para>
    It is possible to check on the accuracy of the planner's estimated costs
266
    by using <command>EXPLAIN ANALYZE</>.  This command actually executes the query,
267
    and then displays the true run time accumulated within each plan node
268
    along with the same estimated costs that a plain <command>EXPLAIN</command> shows.
269 270
    For example, we might get a result like this:

271
<screen>
272 273 274
regression=# EXPLAIN ANALYZE
regression-# SELECT * FROM tenk1 t1, tenk2 t2
regression-# WHERE t1.unique1 &lt; 50 AND t1.unique2 = t2.unique2;
275 276 277 278 279 280 281
                                   QUERY PLAN
-------------------------------------------------------------------------------
 Nested Loop  (cost=0.00..327.02 rows=49 width=296)
                                 (actual time=1.18..29.82 rows=50 loops=1)
   -&gt;  Index Scan using tenk1_unique1 on tenk1 t1
                  (cost=0.00..179.33 rows=49 width=148)
                                 (actual time=0.63..8.91 rows=50 loops=1)
282
         Index Cond: (unique1 &lt; 50)
283 284 285
   -&gt;  Index Scan using tenk2_unique2 on tenk2 t2
                  (cost=0.00..3.01 rows=1 width=148)
                                 (actual time=0.29..0.32 rows=1 loops=50)
286
         Index Cond: ("outer".unique2 = t2.unique2)
287
 Total runtime: 31.60 msec
288
</screen>
289 290 291 292 293 294 295 296 297

    Note that the <quote>actual time</quote> values are in milliseconds of
    real time, whereas the <quote>cost</quote> estimates are expressed in
    arbitrary units of disk fetches; so they are unlikely to match up.
    The thing to pay attention to is the ratios.
   </para>

   <para>
    In some query plans, it is possible for a subplan node to be executed more
298
    than once.  For example, the inner index scan is executed once per outer
299
    row in the above nested-loop plan.  In such cases, the
300 301 302 303 304 305 306 307 308
    <quote>loops</quote> value reports the
    total number of executions of the node, and the actual time and rows
    values shown are averages per-execution.  This is done to make the numbers
    comparable with the way that the cost estimates are shown.  Multiply by
    the <quote>loops</quote> value to get the total time actually spent in
    the node.
   </para>

   <para>
309
    The <literal>Total runtime</literal> shown by <command>EXPLAIN ANALYZE</command> includes
310 311 312
    executor start-up and shut-down time, as well as time spent processing
    the result rows.  It does not include parsing, rewriting, or planning
    time.  For a <command>SELECT</> query, the total run time will normally be just a
313
    little larger than the total time reported for the top-level plan node.
314
    For <command>INSERT</>, <command>UPDATE</>, and <command>DELETE</> commands, the total run time may be
315
    considerably larger, because it includes the time spent processing the
316 317
    result rows.  In these commands, the time for the top plan node
    essentially is the time spent computing the new rows and/or locating
318 319 320
    the old ones, but it doesn't include the time spent making the changes.
   </para>

321
   <para>
322
    It is worth noting that <command>EXPLAIN</> results should not be extrapolated
323 324 325 326 327 328 329 330 331 332
    to situations other than the one you are actually testing; for example,
    results on a toy-sized table can't be assumed to apply to large tables.
    The planner's cost estimates are not linear and so it may well choose
    a different plan for a larger or smaller table.  An extreme example
    is that on a table that only occupies one disk page, you'll nearly
    always get a sequential scan plan whether indexes are available or not.
    The planner realizes that it's going to take one disk page read to
    process the table in any case, so there's no value in expending additional
    page reads to look at an index.
   </para>
333 334
  </sect1>

335
 <sect1 id="planner-stats">
336
  <title>Statistics Used by the Planner</title>
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353

  <para>
   As we saw in the previous section, the query planner needs to estimate
   the number of rows retrieved by a query in order to make good choices
   of query plans.  This section provides a quick look at the statistics
   that the system uses for these estimates.
  </para>

  <para>
   One component of the statistics is the total number of entries in each
   table and index, as well as the number of disk blocks occupied by each
   table and index.  This information is kept in
   <structname>pg_class</structname>'s <structfield>reltuples</structfield>
   and <structfield>relpages</structfield> columns.  We can look at it
   with queries similar to this one:

<screen>
354 355
regression=# SELECT relname, relkind, reltuples, relpages FROM pg_class
regression-# WHERE relname LIKE 'tenk1%';
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
    relname    | relkind | reltuples | relpages
---------------+---------+-----------+----------
 tenk1         | r       |     10000 |      233
 tenk1_hundred | i       |     10000 |       30
 tenk1_unique1 | i       |     10000 |       30
 tenk1_unique2 | i       |     10000 |       30
(4 rows)
</screen>

   Here we can see that <structname>tenk1</structname> contains 10000
   rows, as do its indexes, but the indexes are (unsurprisingly) much
   smaller than the table.
  </para>

  <para>
   For efficiency reasons, <structfield>reltuples</structfield> 
   and <structfield>relpages</structfield> are not updated on-the-fly,
   and so they usually contain only approximate values (which is good
   enough for the planner's purposes).  They are initialized with dummy
   values (presently 1000 and 10 respectively) when a table is created.
   They are updated by certain commands, presently <command>VACUUM</>,
   <command>ANALYZE</>, and <command>CREATE INDEX</>.  A stand-alone
   <command>ANALYZE</>, that is one not part of <command>VACUUM</>,
   generates an approximate <structfield>reltuples</structfield> value
   since it does not read every row of the table.
  </para>

  <para>
   Most queries retrieve only a fraction of the rows in a table, due
385
   to having <literal>WHERE</> clauses that restrict the rows to be examined.
386
   The planner thus needs to make an estimate of the
387 388
   <firstterm>selectivity</> of <literal>WHERE</> clauses, that is, the fraction of
   rows that match each clause of the <literal>WHERE</> condition.  The information
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
   used for this task is stored in the <structname>pg_statistic</structname>
   system catalog.  Entries in <structname>pg_statistic</structname> are
   updated by <command>ANALYZE</> and <command>VACUUM ANALYZE</> commands,
   and are always approximate even when freshly updated.
  </para>

  <para>
   Rather than look at <structname>pg_statistic</structname> directly,
   it's better to look at its view <structname>pg_stats</structname>
   when examining the statistics manually.  <structname>pg_stats</structname>
   is designed to be more easily readable.  Furthermore,
   <structname>pg_stats</structname> is readable by all, whereas
   <structname>pg_statistic</structname> is only readable by the superuser.
   (This prevents unprivileged users from learning something about
   the contents of other people's tables from the statistics.  The
   <structname>pg_stats</structname> view is restricted to show only
   rows about tables that the current user can read.)
   For example, we might do:

<screen>
409
regression=# SELECT attname, n_distinct, most_common_vals FROM pg_stats WHERE tablename = 'road';
410 411 412 413 414 415 416
 attname | n_distinct |                                                                                                                                                                                  most_common_vals                                                                                                                                                                                   
---------+------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 name    |  -0.467008 | {"I- 580                        Ramp","I- 880                        Ramp","Sp Railroad                       ","I- 580                            ","I- 680                        Ramp","I- 80                         Ramp","14th                          St  ","5th                           St  ","Mission                       Blvd","I- 880                            "}
 thepath |         20 | {"[(-122.089,37.71),(-122.0886,37.711)]"}
(2 rows)
regression=#
</screen>
417
  </para>
418

419 420 421
  <para>
   <xref linkend="planner-pg-stats-table"> shows the columns that
   exist in <structname>pg_stats</structname>.
422 423
  </para>

424
  <table id="planner-pg-stats-table">
P
Peter Eisentraut 已提交
425
   <title><structname>pg_stats</structname> Columns</title>
426 427 428 429 430 431 432 433 434 435 436 437

   <tgroup cols=3>
    <thead>
     <row>
      <entry>Name</entry>
      <entry>Type</entry>
      <entry>Description</entry>
     </row>
    </thead>

    <tbody>
     <row>
P
Peter Eisentraut 已提交
438
      <entry><literal>tablename</literal></entry>
439
      <entry><type>name</type></entry>
440
      <entry>Name of the table containing the column</entry>
441 442 443
     </row>

     <row>
P
Peter Eisentraut 已提交
444
      <entry><literal>attname</literal></entry>
445 446 447 448 449
      <entry><type>name</type></entry>
      <entry>Column described by this row</entry>
     </row>

     <row>
P
Peter Eisentraut 已提交
450
      <entry><literal>null_frac</literal></entry>
451
      <entry><type>real</type></entry>
452
      <entry>Fraction of column's entries that are null</entry>
453 454 455
     </row>

     <row>
P
Peter Eisentraut 已提交
456
      <entry><literal>avg_width</literal></entry>
457
      <entry><type>integer</type></entry>
458
      <entry>Average width in bytes of the column's entries</entry>
459 460 461
     </row>

     <row>
P
Peter Eisentraut 已提交
462
      <entry><literal>n_distinct</literal></entry>
463 464 465 466
      <entry><type>real</type></entry>
      <entry>If greater than zero, the estimated number of distinct values
      in the column.  If less than zero, the negative of the number of
      distinct values divided by the number of rows.  (The negated form
467
      is used when <command>ANALYZE</> believes that the number of distinct values
468 469 470 471 472 473 474 475
      is likely to increase as the table grows; the positive form is used
      when the column seems to have a fixed number of possible values.)
      For example, -1 indicates a unique column in which the number of
      distinct values is the same as the number of rows.
      </entry>
     </row>

     <row>
P
Peter Eisentraut 已提交
476
      <entry><literal>most_common_vals</literal></entry>
477 478 479 480 481 482
      <entry><type>text[]</type></entry>
      <entry>A list of the most common values in the column. (Omitted if
      no values seem to be more common than any others.)</entry>
     </row>

     <row>
P
Peter Eisentraut 已提交
483
      <entry><literal>most_common_freqs</literal></entry>
484 485
      <entry><type>real[]</type></entry>
      <entry>A list of the frequencies of the most common values,
486
      i.e., number of occurrences of each divided by total number of rows.
487 488 489 490 491 492 493 494 495
     </entry>
     </row>

     <row>
      <entry>histogram_bounds</entry>
      <entry><type>text[]</type></entry>
      <entry>A list of values that divide the column's values into
      groups of approximately equal population.  The 
      <structfield>most_common_vals</>, if present, are omitted from the
P
Peter Eisentraut 已提交
496
      histogram calculation.  (Omitted if column data type does not have a
497 498 499 500 501 502 503 504 505 506
      <literal>&lt;</> operator, or if the <structfield>most_common_vals</>
      list accounts for the entire population.)
      </entry>
     </row>

     <row>
      <entry>correlation</entry>
      <entry><type>real</type></entry>
      <entry>Statistical correlation between physical row ordering and
      logical ordering of the column values.  This ranges from -1 to +1.
P
Peter Eisentraut 已提交
507
      When the value is near -1 or +1, an index scan on the column will
508
      be estimated to be cheaper than when it is near zero, due to reduction
P
Peter Eisentraut 已提交
509
      of random access to the disk.  (Omitted if column data type does
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
      not have a <literal>&lt;</> operator.)
      </entry>
     </row>
    </tbody>
   </tgroup>
  </table>

  <para>
   The maximum number of entries in the <structfield>most_common_vals</>
   and <structfield>histogram_bounds</> arrays can be set on a
   column-by-column basis using the <command>ALTER TABLE SET STATISTICS</>
   command.  The default limit is presently 10 entries.  Raising the limit
   may allow more accurate planner estimates to be made, particularly for
   columns with irregular data distributions, at the price of consuming
   more space in <structname>pg_statistic</structname> and slightly more
   time to compute the estimates.  Conversely, a lower limit may be
   appropriate for columns with simple data distributions.
  </para>

 </sect1>

531
 <sect1 id="explicit-joins">
P
Peter Eisentraut 已提交
532
  <title>Controlling the Planner with Explicit <literal>JOIN</> Clauses</title>
533 534

  <para>
535 536
   Beginning with <productname>PostgreSQL</productname> 7.1 it has been possible
   to control the query planner to some extent by using the explicit <literal>JOIN</>
537 538 539 540 541
   syntax.  To see why this matters, we first need some background.
  </para>

  <para>
   In a simple join query, such as
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
<programlisting>
SELECT * FROM a, b, c WHERE a.id = b.id AND b.ref = c.id;
</programlisting>
   the planner is free to join the given tables in any order.  For
   example, it could generate a query plan that joins A to B, using
   the <literal>WHERE</> condition <literal>a.id = b.id</>, and then
   joins C to this joined table, using the other <literal>WHERE</>
   condition.  Or it could join B to C and then join A to that result.
   Or it could join A to C and then join them with B --- but that
   would be inefficient, since the full Cartesian product of A and C
   would have to be formed, there being no applicable condition in the
   <literal>WHERE</> clause to allow optimization of the join.  (All
   joins in the <productname>PostgreSQL</productname> executor happen
   between two input tables, so it's necessary to build up the result
   in one or another of these fashions.)  The important point is that
   these different join possibilities give semantically equivalent
   results but may have hugely different execution costs.  Therefore,
   the planner will explore all of them to try to find the most
   efficient query plan.
561 562 563 564 565 566 567 568 569
  </para>

  <para>
   When a query only involves two or three tables, there aren't many join
   orders to worry about.  But the number of possible join orders grows
   exponentially as the number of tables expands.  Beyond ten or so input
   tables it's no longer practical to do an exhaustive search of all the
   possibilities, and even for six or seven tables planning may take an
   annoyingly long time.  When there are too many input tables, the
570
   <productname>PostgreSQL</productname> planner will switch from exhaustive
571
   search to a <firstterm>genetic</firstterm> probabilistic search
572 573
   through a limited number of possibilities.  (The switch-over threshold is
   set by the <varname>GEQO_THRESHOLD</varname> run-time
574
   parameter described in the &cite-admin;.)
575 576 577 578 579 580 581
   The genetic search takes less time, but it won't
   necessarily find the best possible plan.
  </para>

  <para>
   When the query involves outer joins, the planner has much less freedom
   than it does for plain (inner) joins. For example, consider
582
<programlisting>
583
SELECT * FROM a LEFT JOIN (b JOIN c ON (b.ref = c.id)) ON (a.id = b.id);
584
</programlisting>
585 586 587 588 589 590 591 592 593
   Although this query's restrictions are superficially similar to the
   previous example, the semantics are different because a row must be
   emitted for each row of A that has no matching row in the join of B and C.
   Therefore the planner has no choice of join order here: it must join
   B to C and then join A to that result.  Accordingly, this query takes
   less time to plan than the previous query.
  </para>

  <para>
594 595 596 597 598 599 600
   Explicit inner join syntax (<literal>INNER JOIN</>, <literal>CROSS
   JOIN</>, or unadorned <literal>JOIN</>) is semantically the same as
   listing the input relations in <literal>FROM</>, so it does not need to
   constrain the join order.  But it is possible to instruct the
   <productname>PostgreSQL</productname> query planner to treat
   explicit inner <literal>JOIN</>s as constraining the join order anyway.
   For example, these three queries are logically equivalent:
601 602
<programlisting>
SELECT * FROM a, b, c WHERE a.id = b.id AND b.ref = c.id;
603 604
SELECT * FROM a CROSS JOIN b CROSS JOIN c WHERE a.id = b.id AND b.ref = c.id;
SELECT * FROM a JOIN (b JOIN c ON (b.ref = c.id)) ON (a.id = b.id);
605
</programlisting>
606
   But if we tell the planner to honor the <literal>JOIN</> order,
T
Tom Lane 已提交
607
   the second and third take less time to plan than the first.  This effect
608 609 610 611
   is not worth worrying about for only three tables, but it can be a
   lifesaver with many tables.
  </para>

612 613 614 615 616 617
  <para>
   To force the planner to follow the <literal>JOIN</> order for inner joins,
   set the <varname>JOIN_COLLAPSE_LIMIT</> run-time parameter to 1.
   (Other possible values are discussed below.)
  </para>

618 619
  <para>
   You do not need to constrain the join order completely in order to
620 621
   cut search time, because it's OK to use <literal>JOIN</> operators
   within items of a plain <literal>FROM</> list.  For example, consider
622
<programlisting>
623
SELECT * FROM a CROSS JOIN b, c, d, e WHERE ...;
624
</programlisting>
625
   With <varname>JOIN_COLLAPSE_LIMIT</> = 1, this
626 627 628 629 630 631
   forces the planner to join A to B before joining them to other tables,
   but doesn't constrain its choices otherwise.  In this example, the
   number of possible join orders is reduced by a factor of 5.
  </para>

  <para>
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
   Constraining the planner's search in this way is a useful technique
   both for reducing planning time and for directing the planner to a
   good query plan.  If the planner chooses a bad join order by default,
   you can force it to choose a better order via <literal>JOIN</> syntax
   --- assuming that you know of a better order, that is.  Experimentation
   is recommended.
  </para>

  <para>
   A closely related issue that affects planning time is collapsing of
   sub-SELECTs into their parent query.  For example, consider
<programlisting>
SELECT *
FROM x, y,
     (SELECT * FROM a, b, c WHERE something) AS ss
WHERE somethingelse
</programlisting>
   This situation might arise from use of a view that contains a join;
   the view's SELECT rule will be inserted in place of the view reference,
   yielding a query much like the above.  Normally, the planner will try
   to collapse the sub-query into the parent, yielding
653
<programlisting>
654
SELECT * FROM x, y, a, b, c WHERE something AND somethingelse
655
</programlisting>
656 657 658 659 660 661 662 663 664 665 666 667
   This usually results in a better plan than planning the sub-query
   separately.  (For example, the outer WHERE conditions might be such that
   joining X to A first eliminates many rows of A, thus avoiding the need to
   form the full logical output of the sub-select.)  But at the same time,
   we have increased the planning time; here, we have a five-way join
   problem replacing two separate three-way join problems.  Because of the
   exponential growth of the number of possibilities, this makes a big
   difference.  The planner tries to avoid getting stuck in huge join search
   problems by not collapsing a sub-query if more than
   <varname>FROM_COLLAPSE_LIMIT</> FROM-items would result in the parent
   query.  You can trade off planning time against quality of plan by
   adjusting this run-time parameter up or down.
668 669 670
  </para>

  <para>
671 672 673 674 675 676 677 678 679 680
   <varname>FROM_COLLAPSE_LIMIT</> and <varname>JOIN_COLLAPSE_LIMIT</>
   are similarly named because they do almost the same thing: one controls
   when the planner will <quote>flatten out</> sub-SELECTs, and the
   other controls when it will flatten out explicit inner JOINs.  Typically
   you would either set <varname>JOIN_COLLAPSE_LIMIT</> equal to
   <varname>FROM_COLLAPSE_LIMIT</> (so that explicit JOINs and sub-SELECTs
   act similarly) or set <varname>JOIN_COLLAPSE_LIMIT</> to 1 (if you want
   to control join order with explicit JOINs).  But you might set them
   differently if you are trying to fine-tune the tradeoff between planning
   time and run time.
681 682 683 684 685 686 687 688 689 690 691 692 693
  </para>
 </sect1>

 <sect1 id="populate">
  <title>Populating a Database</title>

  <para>
   One may need to do a large number of table insertions when first
   populating a database. Here are some tips and techniques for making that as
   efficient as possible.
  </para>

  <sect2 id="disable-autocommit">
P
Peter Eisentraut 已提交
694
   <title>Disable Autocommit</title>
695 696

   <para>
P
Peter Eisentraut 已提交
697
    Turn off autocommit and just do one commit at
698 699 700 701 702
    the end.  (In plain SQL, this means issuing <command>BEGIN</command>
    at the start and <command>COMMIT</command> at the end.  Some client
    libraries may do this behind your back, in which case you need to
    make sure the library does it when you want it done.)
    If you allow each insertion to be committed separately,
703
    <productname>PostgreSQL</productname> is doing a lot of work for each
704
    record added.
705 706 707 708
    An additional benefit of doing all insertions in one transaction
    is that if the insertion of one record were to fail then the
    insertion of all records inserted up to that point would be rolled
    back, so you won't be stuck with partially loaded data.
709 710 711 712 713 714 715 716
   </para>
  </sect2>

  <sect2 id="populate-copy-from">
   <title>Use COPY FROM</title>

   <para>
    Use <command>COPY FROM STDIN</command> to load all the records in one
717 718
    command, instead of using
    a series of <command>INSERT</command> commands.  This reduces parsing,
P
Peter Eisentraut 已提交
719 720 721
    planning, etc.
    overhead a great deal. If you do this then it is not necessary to turn
    off autocommit, since it is only one command anyway.
722 723 724
   </para>
  </sect2>

725 726
  <sect2 id="populate-rm-indexes">
   <title>Remove Indexes</title>
727 728 729

   <para>
    If you are loading a freshly created table, the fastest way is to
730 731
    create the table, bulk-load with <command>COPY</command>, then create any
    indexes needed 
732 733 734 735 736 737
    for the table.  Creating an index on pre-existing data is quicker than
    updating it incrementally as each record is loaded.
   </para>

   <para>
    If you are augmenting an existing table, you can <command>DROP
738
    INDEX</command>, load the table, then recreate the index. Of
739
    course, the database performance for other users may be adversely 
740
    affected during the time that the index is missing.  One should also
P
Peter Eisentraut 已提交
741 742
    think twice before dropping unique indexes, since the error checking
    afforded by the unique constraint will be lost while the index is missing.
743 744 745 746
   </para>
  </sect2>

  <sect2 id="populate-analyze">
747
   <title>Run ANALYZE Afterwards</title>
748 749 750 751 752 753 754 755

   <para>
    It's a good idea to run <command>ANALYZE</command> or <command>VACUUM
    ANALYZE</command> anytime you've added or updated a lot of data,
    including just after initially populating a table.  This ensures that
    the planner has up-to-date statistics about the table.  With no statistics
    or obsolete statistics, the planner may make poor choices of query plans,
    leading to bad performance on queries that use your table.
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
   </para>
  </sect2>
  </sect1>

 </chapter>

<!-- Keep this comment at the end of the file
Local variables:
mode:sgml
sgml-omittag:nil
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
sgml-parent-document:nil
sgml-default-dtd-file:"./reference.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:("/usr/lib/sgml/catalog")
sgml-local-ecat-files:nil
End:
-->