~vcs-imports/mammoth-replicator/trunk

« back to all changes in this revision

Viewing changes to doc/src/sgml/perform.sgml

  • Committer: alvherre
  • Date: 2005-12-16 21:24:52 UTC
  • Revision ID: svn-v4:db760fc0-0f08-0410-9d63-cc6633f64896:trunk:1
Initial import of the REL8_0_3 sources from the Pgsql CVS repository.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
<!--
 
2
$PostgreSQL: pgsql/doc/src/sgml/perform.sgml,v 1.49 2004-12-23 23:07:38 tgl Exp $
 
3
-->
 
4
 
 
5
 <chapter id="performance-tips">
 
6
  <title>Performance Tips</title>
 
7
 
 
8
  <indexterm zone="performance-tips">
 
9
   <primary>performance</primary>
 
10
  </indexterm>
 
11
 
 
12
  <para>
 
13
   Query performance can be affected by many things. Some of these can 
 
14
   be manipulated by the user, while others are fundamental to the underlying
 
15
   design of the system.  This chapter provides some hints about understanding
 
16
   and tuning <productname>PostgreSQL</productname> performance.
 
17
  </para>
 
18
 
 
19
  <sect1 id="using-explain">
 
20
   <title>Using <command>EXPLAIN</command></title>
 
21
 
 
22
   <indexterm zone="using-explain">
 
23
    <primary>EXPLAIN</primary>
 
24
   </indexterm>
 
25
 
 
26
   <indexterm zone="using-explain">
 
27
    <primary>query plan</primary>
 
28
   </indexterm>
 
29
 
 
30
   <para>
 
31
    <productname>PostgreSQL</productname> devises a <firstterm>query
 
32
    plan</firstterm> for each query it is given.  Choosing the right
 
33
    plan to match the query structure and the properties of the data
 
34
    is absolutely critical for good performance.  You can use the
 
35
    <xref linkend="sql-explain" endterm="sql-explain-title"> command
 
36
    to see what query plan the system creates for any query.
 
37
    Plan-reading is an art that deserves an extensive tutorial, which
 
38
    this is not; but here is some basic information.
 
39
   </para>
 
40
 
 
41
   <para>
 
42
    The numbers that are currently quoted by <command>EXPLAIN</command> are:
 
43
 
 
44
    <itemizedlist>
 
45
     <listitem>
 
46
      <para>
 
47
       Estimated start-up cost (Time expended before output scan can start,
 
48
       e.g., time to do the sorting in a sort node.)
 
49
      </para>
 
50
     </listitem>
 
51
 
 
52
     <listitem>
 
53
      <para>
 
54
       Estimated total cost (If all rows were to be retrieved, which they may not
 
55
       be: a query with a <literal>LIMIT</> clause will stop short of paying the total cost,
 
56
       for example.)
 
57
      </para>
 
58
     </listitem>
 
59
 
 
60
     <listitem>
 
61
      <para>
 
62
       Estimated number of rows output by this plan node (Again, only if
 
63
       executed to completion)
 
64
      </para>
 
65
     </listitem>
 
66
 
 
67
     <listitem>
 
68
      <para>
 
69
       Estimated average width (in bytes) of rows output by this plan
 
70
       node
 
71
      </para>
 
72
     </listitem>
 
73
    </itemizedlist>
 
74
   </para>
 
75
 
 
76
   <para>
 
77
    The costs are measured in units of disk page fetches.  (CPU effort
 
78
    estimates are converted into disk-page units using some
 
79
    fairly arbitrary fudge factors. If you want to experiment with these
 
80
    factors, see the list of run-time configuration parameters in
 
81
    <xref linkend="runtime-config-query-constants">.)
 
82
   </para>
 
83
 
 
84
   <para>
 
85
    It's important to note that the cost of an upper-level node includes
 
86
    the cost of all its child nodes.  It's also important to realize that
 
87
    the cost only reflects things that the planner/optimizer cares about.
 
88
    In particular, the cost does not consider the time spent transmitting
 
89
    result rows to the frontend, which could be a pretty dominant
 
90
    factor in the true elapsed time; but the planner ignores it because
 
91
    it cannot change it by altering the plan.  (Every correct plan will
 
92
    output the same row set, we trust.)
 
93
   </para>
 
94
 
 
95
   <para>
 
96
    Rows output is a little tricky because it is <emphasis>not</emphasis> the
 
97
    number of rows
 
98
    processed/scanned by the query, it is usually less, reflecting the
 
99
    estimated selectivity of any <literal>WHERE</>-clause conditions that are being
 
100
    applied at this node.  Ideally the top-level rows estimate will
 
101
    approximate the number of rows actually returned, updated, or deleted
 
102
    by the query.
 
103
   </para>
 
104
 
 
105
   <para>
 
106
    Here are some examples (using the regression test database after a
 
107
    <command>VACUUM ANALYZE</>, and 7.3 development sources):
 
108
 
 
109
<programlisting>
 
110
EXPLAIN SELECT * FROM tenk1;
 
111
 
 
112
                         QUERY PLAN
 
113
-------------------------------------------------------------
 
114
 Seq Scan on tenk1  (cost=0.00..333.00 rows=10000 width=148)
 
115
</programlisting>
 
116
   </para>
 
117
 
 
118
   <para>
 
119
    This is about as straightforward as it gets.  If you do
 
120
 
 
121
<programlisting>
 
122
SELECT * FROM pg_class WHERE relname = 'tenk1';
 
123
</programlisting>
 
124
 
 
125
    you will find out that <classname>tenk1</classname> has 233 disk
 
126
    pages and 10000 rows.  So the cost is estimated at 233 page
 
127
    reads, defined as costing 1.0 apiece, plus 10000 * <xref
 
128
    linkend="guc-cpu-tuple-cost"> which is
 
129
    currently 0.01 (try <command>SHOW cpu_tuple_cost</command>).
 
130
   </para>
 
131
 
 
132
   <para>
 
133
    Now let's modify the query to add a <literal>WHERE</> condition:
 
134
 
 
135
<programlisting>
 
136
EXPLAIN SELECT * FROM tenk1 WHERE unique1 &lt; 1000;
 
137
 
 
138
                         QUERY PLAN
 
139
------------------------------------------------------------
 
140
 Seq Scan on tenk1  (cost=0.00..358.00 rows=1033 width=148)
 
141
   Filter: (unique1 &lt; 1000)
 
142
</programlisting>
 
143
 
 
144
    The estimate of output rows has gone down because of the <literal>WHERE</> clause.
 
145
    However, the scan will still have to visit all 10000 rows, so the cost
 
146
    hasn't decreased; in fact it has gone up a bit to reflect the extra CPU
 
147
    time spent checking the <literal>WHERE</> condition.
 
148
   </para>
 
149
 
 
150
   <para>
 
151
    The actual number of rows this query would select is 1000, but the
 
152
    estimate is only approximate.  If you try to duplicate this experiment,
 
153
    you will probably get a slightly different estimate; moreover, it will
 
154
    change after each <command>ANALYZE</command> command, because the
 
155
    statistics produced by <command>ANALYZE</command> are taken from a
 
156
    randomized sample of the table.
 
157
   </para>
 
158
 
 
159
   <para>
 
160
    Modify the query to restrict the condition even more:
 
161
 
 
162
<programlisting>
 
163
EXPLAIN SELECT * FROM tenk1 WHERE unique1 &lt; 50;
 
164
 
 
165
                                   QUERY PLAN
 
166
-------------------------------------------------------------------------------
 
167
 Index Scan using tenk1_unique1 on tenk1  (cost=0.00..179.33 rows=49 width=148)
 
168
   Index Cond: (unique1 &lt; 50)
 
169
</programlisting>
 
170
 
 
171
    and you will see that if we make the <literal>WHERE</> condition selective
 
172
    enough, the planner will
 
173
    eventually decide that an index scan is cheaper than a sequential scan.
 
174
    This plan will only have to visit 50 rows because of the index,
 
175
    so it wins despite the fact that each individual fetch is more expensive
 
176
    than reading a whole disk page sequentially.
 
177
   </para>
 
178
 
 
179
   <para>
 
180
    Add another condition to the <literal>WHERE</> clause:
 
181
 
 
182
<programlisting>
 
183
EXPLAIN SELECT * FROM tenk1 WHERE unique1 &lt; 50 AND stringu1 = 'xxx';
 
184
 
 
185
                                  QUERY PLAN
 
186
-------------------------------------------------------------------------------
 
187
 Index Scan using tenk1_unique1 on tenk1  (cost=0.00..179.45 rows=1 width=148)
 
188
   Index Cond: (unique1 &lt; 50)
 
189
   Filter: (stringu1 = 'xxx'::name)
 
190
</programlisting>
 
191
 
 
192
    The added condition <literal>stringu1 = 'xxx'</literal> reduces the
 
193
    output-rows estimate, but not the cost because we still have to visit the
 
194
    same set of rows.  Notice that the <literal>stringu1</> clause
 
195
    cannot be applied as an index condition (since this index is only on
 
196
    the <literal>unique1</> column).  Instead it is applied as a filter on
 
197
    the rows retrieved by the index.  Thus the cost has actually gone up
 
198
    a little bit to reflect this extra checking.
 
199
   </para>
 
200
 
 
201
   <para>
 
202
    Let's try joining two tables, using the columns we have been discussing:
 
203
 
 
204
<programlisting>
 
205
EXPLAIN SELECT * FROM tenk1 t1, tenk2 t2 WHERE t1.unique1 &lt; 50 AND t1.unique2 = t2.unique2;
 
206
 
 
207
                               QUERY PLAN
 
208
----------------------------------------------------------------------------
 
209
 Nested Loop  (cost=0.00..327.02 rows=49 width=296)
 
210
   -&gt;  Index Scan using tenk1_unique1 on tenk1 t1
 
211
                                      (cost=0.00..179.33 rows=49 width=148)
 
212
         Index Cond: (unique1 &lt; 50)
 
213
   -&gt;  Index Scan using tenk2_unique2 on tenk2 t2
 
214
                                      (cost=0.00..3.01 rows=1 width=148)
 
215
         Index Cond: ("outer".unique2 = t2.unique2)
 
216
</programlisting>
 
217
   </para>
 
218
 
 
219
   <para>
 
220
    In this nested-loop join, the outer scan is the same index scan we had
 
221
    in the example before last, and so its cost and row count are the same
 
222
    because we are applying the <literal>WHERE</> clause <literal>unique1 &lt; 50</literal> at that node.
 
223
    The <literal>t1.unique2 = t2.unique2</literal> clause is not relevant yet, so it doesn't
 
224
    affect row count of the outer scan.  For the inner scan, the <literal>unique2</> value of the
 
225
    current
 
226
    outer-scan row is plugged into the inner index scan
 
227
    to produce an index condition like
 
228
    <literal>t2.unique2 = <replaceable>constant</replaceable></literal>.  So we get the
 
229
     same inner-scan plan and costs that we'd get from, say, <literal>EXPLAIN SELECT
 
230
     * FROM tenk2 WHERE unique2 = 42</literal>.  The costs of the loop node are then set
 
231
     on the basis of the cost of the outer scan, plus one repetition of the
 
232
     inner scan for each outer row (49 * 3.01, here), plus a little CPU
 
233
     time for join processing.
 
234
   </para>
 
235
 
 
236
   <para>
 
237
    In this example the join's output row count is the same as the product
 
238
    of the two scans' row counts, but that's not true in general, because
 
239
    in general you can have <literal>WHERE</> clauses that mention both tables and
 
240
    so can only be applied at the join point, not to either input scan.
 
241
    For example, if we added <literal>WHERE ... AND t1.hundred &lt; t2.hundred</literal>,
 
242
    that would decrease the output row count of the join node, but not change
 
243
    either input scan.
 
244
   </para>
 
245
 
 
246
   <para>
 
247
    One way to look at variant plans is to force the planner to disregard
 
248
    whatever strategy it thought was the winner, using the enable/disable
 
249
    flags for each plan type.  (This is a crude tool, but useful.  See
 
250
    also <xref linkend="explicit-joins">.)
 
251
 
 
252
<programlisting>
 
253
SET enable_nestloop = off;
 
254
EXPLAIN SELECT * FROM tenk1 t1, tenk2 t2 WHERE t1.unique1 &lt; 50 AND t1.unique2 = t2.unique2;
 
255
 
 
256
                               QUERY PLAN
 
257
--------------------------------------------------------------------------
 
258
 Hash Join  (cost=179.45..563.06 rows=49 width=296)
 
259
   Hash Cond: ("outer".unique2 = "inner".unique2)
 
260
   -&gt;  Seq Scan on tenk2 t2  (cost=0.00..333.00 rows=10000 width=148)
 
261
   -&gt;  Hash  (cost=179.33..179.33 rows=49 width=148)
 
262
         -&gt;  Index Scan using tenk1_unique1 on tenk1 t1
 
263
                                    (cost=0.00..179.33 rows=49 width=148)
 
264
               Index Cond: (unique1 &lt; 50)
 
265
</programlisting>
 
266
 
 
267
    This plan proposes to extract the 50 interesting rows of <classname>tenk1</classname>
 
268
    using ye same olde index scan, stash them into an in-memory hash table,
 
269
    and then do a sequential scan of <classname>tenk2</classname>, probing into the hash table
 
270
    for possible matches of <literal>t1.unique2 = t2.unique2</literal> at each <classname>tenk2</classname> row.
 
271
    The cost to read <classname>tenk1</classname> and set up the hash table is entirely start-up
 
272
    cost for the hash join, since we won't get any rows out until we can
 
273
    start reading <classname>tenk2</classname>.  The total time estimate for the join also
 
274
    includes a hefty charge for the CPU time to probe the hash table
 
275
    10000 times.  Note, however, that we are <emphasis>not</emphasis> charging 10000 times 179.33;
 
276
    the hash table setup is only done once in this plan type.
 
277
   </para>
 
278
 
 
279
   <para>
 
280
    It is possible to check on the accuracy of the planner's estimated costs
 
281
    by using <command>EXPLAIN ANALYZE</>.  This command actually executes the query,
 
282
    and then displays the true run time accumulated within each plan node
 
283
    along with the same estimated costs that a plain <command>EXPLAIN</command> shows.
 
284
    For example, we might get a result like this:
 
285
 
 
286
<screen>
 
287
EXPLAIN ANALYZE SELECT * FROM tenk1 t1, tenk2 t2 WHERE t1.unique1 &lt; 50 AND t1.unique2 = t2.unique2;
 
288
 
 
289
                                   QUERY PLAN
 
290
-------------------------------------------------------------------------------
 
291
 Nested Loop  (cost=0.00..327.02 rows=49 width=296)
 
292
                                 (actual time=1.181..29.822 rows=50 loops=1)
 
293
   -&gt;  Index Scan using tenk1_unique1 on tenk1 t1
 
294
                  (cost=0.00..179.33 rows=49 width=148)
 
295
                                 (actual time=0.630..8.917 rows=50 loops=1)
 
296
         Index Cond: (unique1 &lt; 50)
 
297
   -&gt;  Index Scan using tenk2_unique2 on tenk2 t2
 
298
                  (cost=0.00..3.01 rows=1 width=148)
 
299
                                 (actual time=0.295..0.324 rows=1 loops=50)
 
300
         Index Cond: ("outer".unique2 = t2.unique2)
 
301
 Total runtime: 31.604 ms
 
302
</screen>
 
303
 
 
304
    Note that the <quote>actual time</quote> values are in milliseconds of
 
305
    real time, whereas the <quote>cost</quote> estimates are expressed in
 
306
    arbitrary units of disk fetches; so they are unlikely to match up.
 
307
    The thing to pay attention to is the ratios.
 
308
   </para>
 
309
 
 
310
   <para>
 
311
    In some query plans, it is possible for a subplan node to be executed more
 
312
    than once.  For example, the inner index scan is executed once per outer
 
313
    row in the above nested-loop plan.  In such cases, the
 
314
    <quote>loops</quote> value reports the
 
315
    total number of executions of the node, and the actual time and rows
 
316
    values shown are averages per-execution.  This is done to make the numbers
 
317
    comparable with the way that the cost estimates are shown.  Multiply by
 
318
    the <quote>loops</quote> value to get the total time actually spent in
 
319
    the node.
 
320
   </para>
 
321
 
 
322
   <para>
 
323
    The <literal>Total runtime</literal> shown by <command>EXPLAIN ANALYZE</command> includes
 
324
    executor start-up and shut-down time, as well as time spent processing
 
325
    the result rows.  It does not include parsing, rewriting, or planning
 
326
    time.  For a <command>SELECT</> query, the total run time will normally be just a
 
327
    little larger than the total time reported for the top-level plan node.
 
328
    For <command>INSERT</>, <command>UPDATE</>, and <command>DELETE</> commands, the total run time may be
 
329
    considerably larger, because it includes the time spent processing the
 
330
    result rows.  In these commands, the time for the top plan node
 
331
    essentially is the time spent computing the new rows and/or locating
 
332
    the old ones, but it doesn't include the time spent making the changes.
 
333
   </para>
 
334
 
 
335
   <para>
 
336
    It is worth noting that <command>EXPLAIN</> results should not be extrapolated
 
337
    to situations other than the one you are actually testing; for example,
 
338
    results on a toy-sized table can't be assumed to apply to large tables.
 
339
    The planner's cost estimates are not linear and so it may well choose
 
340
    a different plan for a larger or smaller table.  An extreme example
 
341
    is that on a table that only occupies one disk page, you'll nearly
 
342
    always get a sequential scan plan whether indexes are available or not.
 
343
    The planner realizes that it's going to take one disk page read to
 
344
    process the table in any case, so there's no value in expending additional
 
345
    page reads to look at an index.
 
346
   </para>
 
347
  </sect1>
 
348
 
 
349
 <sect1 id="planner-stats">
 
350
  <title>Statistics Used by the Planner</title>
 
351
 
 
352
  <indexterm zone="planner-stats">
 
353
   <primary>statistics</primary>
 
354
   <secondary>of the planner</secondary>
 
355
  </indexterm>
 
356
 
 
357
  <para>
 
358
   As we saw in the previous section, the query planner needs to estimate
 
359
   the number of rows retrieved by a query in order to make good choices
 
360
   of query plans.  This section provides a quick look at the statistics
 
361
   that the system uses for these estimates.
 
362
  </para>
 
363
 
 
364
  <para>
 
365
   One component of the statistics is the total number of entries in each
 
366
   table and index, as well as the number of disk blocks occupied by each
 
367
   table and index.  This information is kept in the table
 
368
   <structname>pg_class</structname> in the columns <structfield>reltuples</structfield>
 
369
   and <structfield>relpages</structfield>.  We can look at it
 
370
   with queries similar to this one:
 
371
 
 
372
<screen>
 
373
SELECT relname, relkind, reltuples, relpages FROM pg_class WHERE relname LIKE 'tenk1%';
 
374
 
 
375
    relname    | relkind | reltuples | relpages
 
376
---------------+---------+-----------+----------
 
377
 tenk1         | r       |     10000 |      233
 
378
 tenk1_hundred | i       |     10000 |       30
 
379
 tenk1_unique1 | i       |     10000 |       30
 
380
 tenk1_unique2 | i       |     10000 |       30
 
381
(4 rows)
 
382
</screen>
 
383
 
 
384
   Here we can see that <structname>tenk1</structname> contains 10000
 
385
   rows, as do its indexes, but the indexes are (unsurprisingly) much
 
386
   smaller than the table.
 
387
  </para>
 
388
 
 
389
  <para>
 
390
   For efficiency reasons, <structfield>reltuples</structfield> 
 
391
   and <structfield>relpages</structfield> are not updated on-the-fly,
 
392
   and so they usually contain somewhat out-of-date values.
 
393
   They are updated by <command>VACUUM</>, <command>ANALYZE</>, and a
 
394
   few DDL commands such as <command>CREATE INDEX</>.  A stand-alone
 
395
   <command>ANALYZE</>, that is one not part of <command>VACUUM</>,
 
396
   generates an approximate <structfield>reltuples</structfield> value
 
397
   since it does not read every row of the table.  The planner
 
398
   will scale the values it finds in <structname>pg_class</structname>
 
399
   to match the current physical table size, thus obtaining a closer
 
400
   approximation.
 
401
  </para>
 
402
 
 
403
  <indexterm>
 
404
   <primary>pg_statistic</primary>
 
405
  </indexterm>
 
406
 
 
407
  <para>
 
408
   Most queries retrieve only a fraction of the rows in a table, due
 
409
   to having <literal>WHERE</> clauses that restrict the rows to be examined.
 
410
   The planner thus needs to make an estimate of the
 
411
   <firstterm>selectivity</> of <literal>WHERE</> clauses, that is, the fraction of
 
412
   rows that match each condition in the <literal>WHERE</> clause.  The information
 
413
   used for this task is stored in the <structname>pg_statistic</structname>
 
414
   system catalog.  Entries in <structname>pg_statistic</structname> are
 
415
   updated by <command>ANALYZE</> and <command>VACUUM ANALYZE</> commands
 
416
   and are always approximate even when freshly updated.
 
417
  </para>
 
418
 
 
419
  <indexterm>
 
420
   <primary>pg_stats</primary>
 
421
  </indexterm>
 
422
 
 
423
  <para>
 
424
   Rather than look at <structname>pg_statistic</structname> directly,
 
425
   it's better to look at its view <structname>pg_stats</structname>
 
426
   when examining the statistics manually.  <structname>pg_stats</structname>
 
427
   is designed to be more easily readable.  Furthermore,
 
428
   <structname>pg_stats</structname> is readable by all, whereas
 
429
   <structname>pg_statistic</structname> is only readable by a superuser.
 
430
   (This prevents unprivileged users from learning something about
 
431
   the contents of other people's tables from the statistics.  The
 
432
   <structname>pg_stats</structname> view is restricted to show only
 
433
   rows about tables that the current user can read.)
 
434
   For example, we might do:
 
435
 
 
436
<screen>
 
437
SELECT attname, n_distinct, most_common_vals FROM pg_stats WHERE tablename = 'road';
 
438
 
 
439
 attname | n_distinct |                                                                                                                                                                                  most_common_vals                                                                                                                                                                                   
 
440
---------+------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 
441
 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                            "}
 
442
 thepath |         20 | {"[(-122.089,37.71),(-122.0886,37.711)]"}
 
443
(2 rows)
 
444
</screen>
 
445
  </para>
 
446
 
 
447
  <para>
 
448
   <structname>pg_stats</structname> is described in detail in
 
449
   <xref linkend="view-pg-stats">.
 
450
  </para>
 
451
 
 
452
  <para>
 
453
   The amount of information stored in <structname>pg_statistic</structname>,
 
454
   in particular the maximum number of entries in the
 
455
   <structfield>most_common_vals</> and <structfield>histogram_bounds</>
 
456
   arrays for each column, can be set on a
 
457
   column-by-column basis using the <command>ALTER TABLE SET STATISTICS</>
 
458
   command, or globally by setting the
 
459
   <xref linkend="guc-default-statistics-target"> configuration variable.
 
460
   The default limit is presently 10 entries.  Raising the limit
 
461
   may allow more accurate planner estimates to be made, particularly for
 
462
   columns with irregular data distributions, at the price of consuming
 
463
   more space in <structname>pg_statistic</structname> and slightly more
 
464
   time to compute the estimates.  Conversely, a lower limit may be
 
465
   appropriate for columns with simple data distributions.
 
466
  </para>
 
467
 
 
468
 </sect1>
 
469
 
 
470
 <sect1 id="explicit-joins">
 
471
  <title>Controlling the Planner with Explicit <literal>JOIN</> Clauses</title>
 
472
 
 
473
  <indexterm zone="explicit-joins">
 
474
   <primary>join</primary>
 
475
   <secondary>controlling the order</secondary>
 
476
  </indexterm>
 
477
 
 
478
  <para>
 
479
   It is possible
 
480
   to control the query planner to some extent by using the explicit <literal>JOIN</>
 
481
   syntax.  To see why this matters, we first need some background.
 
482
  </para>
 
483
 
 
484
  <para>
 
485
   In a simple join query, such as
 
486
<programlisting>
 
487
SELECT * FROM a, b, c WHERE a.id = b.id AND b.ref = c.id;
 
488
</programlisting>
 
489
   the planner is free to join the given tables in any order.  For
 
490
   example, it could generate a query plan that joins A to B, using
 
491
   the <literal>WHERE</> condition <literal>a.id = b.id</>, and then
 
492
   joins C to this joined table, using the other <literal>WHERE</>
 
493
   condition.  Or it could join B to C and then join A to that result.
 
494
   Or it could join A to C and then join them with B, but that
 
495
   would be inefficient, since the full Cartesian product of A and C
 
496
   would have to be formed, there being no applicable condition in the
 
497
   <literal>WHERE</> clause to allow optimization of the join.  (All
 
498
   joins in the <productname>PostgreSQL</productname> executor happen
 
499
   between two input tables, so it's necessary to build up the result
 
500
   in one or another of these fashions.)  The important point is that
 
501
   these different join possibilities give semantically equivalent
 
502
   results but may have hugely different execution costs.  Therefore,
 
503
   the planner will explore all of them to try to find the most
 
504
   efficient query plan.
 
505
  </para>
 
506
 
 
507
  <para>
 
508
   When a query only involves two or three tables, there aren't many join
 
509
   orders to worry about.  But the number of possible join orders grows
 
510
   exponentially as the number of tables expands.  Beyond ten or so input
 
511
   tables it's no longer practical to do an exhaustive search of all the
 
512
   possibilities, and even for six or seven tables planning may take an
 
513
   annoyingly long time.  When there are too many input tables, the
 
514
   <productname>PostgreSQL</productname> planner will switch from exhaustive
 
515
   search to a <firstterm>genetic</firstterm> probabilistic search
 
516
   through a limited number of possibilities.  (The switch-over threshold is
 
517
   set by the <xref linkend="guc-geqo-threshold"> run-time
 
518
   parameter.)
 
519
   The genetic search takes less time, but it won't
 
520
   necessarily find the best possible plan.
 
521
  </para>
 
522
 
 
523
  <para>
 
524
   When the query involves outer joins, the planner has much less freedom
 
525
   than it does for plain (inner) joins. For example, consider
 
526
<programlisting>
 
527
SELECT * FROM a LEFT JOIN (b JOIN c ON (b.ref = c.id)) ON (a.id = b.id);
 
528
</programlisting>
 
529
   Although this query's restrictions are superficially similar to the
 
530
   previous example, the semantics are different because a row must be
 
531
   emitted for each row of A that has no matching row in the join of B and C.
 
532
   Therefore the planner has no choice of join order here: it must join
 
533
   B to C and then join A to that result.  Accordingly, this query takes
 
534
   less time to plan than the previous query.
 
535
  </para>
 
536
 
 
537
  <para>
 
538
   Explicit inner join syntax (<literal>INNER JOIN</>, <literal>CROSS
 
539
   JOIN</>, or unadorned <literal>JOIN</>) is semantically the same as
 
540
   listing the input relations in <literal>FROM</>, so it does not need to
 
541
   constrain the join order.  But it is possible to instruct the
 
542
   <productname>PostgreSQL</productname> query planner to treat
 
543
   explicit inner <literal>JOIN</>s as constraining the join order anyway.
 
544
   For example, these three queries are logically equivalent:
 
545
<programlisting>
 
546
SELECT * FROM a, b, c WHERE a.id = b.id AND b.ref = c.id;
 
547
SELECT * FROM a CROSS JOIN b CROSS JOIN c WHERE a.id = b.id AND b.ref = c.id;
 
548
SELECT * FROM a JOIN (b JOIN c ON (b.ref = c.id)) ON (a.id = b.id);
 
549
</programlisting>
 
550
   But if we tell the planner to honor the <literal>JOIN</> order,
 
551
   the second and third take less time to plan than the first.  This effect
 
552
   is not worth worrying about for only three tables, but it can be a
 
553
   lifesaver with many tables.
 
554
  </para>
 
555
 
 
556
  <para>
 
557
   To force the planner to follow the <literal>JOIN</> order for inner joins,
 
558
   set the <xref linkend="guc-join-collapse-limit"> run-time parameter to 1.
 
559
   (Other possible values are discussed below.)
 
560
  </para>
 
561
 
 
562
  <para>
 
563
   You do not need to constrain the join order completely in order to
 
564
   cut search time, because it's OK to use <literal>JOIN</> operators
 
565
   within items of a plain <literal>FROM</> list.  For example, consider
 
566
<programlisting>
 
567
SELECT * FROM a CROSS JOIN b, c, d, e WHERE ...;
 
568
</programlisting>
 
569
   With <varname>join_collapse_limit</> = 1, this
 
570
   forces the planner to join A to B before joining them to other tables,
 
571
   but doesn't constrain its choices otherwise.  In this example, the
 
572
   number of possible join orders is reduced by a factor of 5.
 
573
  </para>
 
574
 
 
575
  <para>
 
576
   Constraining the planner's search in this way is a useful technique
 
577
   both for reducing planning time and for directing the planner to a
 
578
   good query plan.  If the planner chooses a bad join order by default,
 
579
   you can force it to choose a better order via <literal>JOIN</> syntax
 
580
   &mdash; assuming that you know of a better order, that is.  Experimentation
 
581
   is recommended.
 
582
  </para>
 
583
 
 
584
  <para>
 
585
   A closely related issue that affects planning time is collapsing of
 
586
   subqueries into their parent query.  For example, consider
 
587
<programlisting>
 
588
SELECT *
 
589
FROM x, y,
 
590
    (SELECT * FROM a, b, c WHERE something) AS ss
 
591
WHERE somethingelse;
 
592
</programlisting>
 
593
   This situation might arise from use of a view that contains a join;
 
594
   the view's <literal>SELECT</> rule will be inserted in place of the view reference,
 
595
   yielding a query much like the above.  Normally, the planner will try
 
596
   to collapse the subquery into the parent, yielding
 
597
<programlisting>
 
598
SELECT * FROM x, y, a, b, c WHERE something AND somethingelse;
 
599
</programlisting>
 
600
   This usually results in a better plan than planning the subquery
 
601
   separately.  (For example, the outer <literal>WHERE</> conditions might be such that
 
602
   joining X to A first eliminates many rows of A, thus avoiding the need to
 
603
   form the full logical output of the subquery.)  But at the same time,
 
604
   we have increased the planning time; here, we have a five-way join
 
605
   problem replacing two separate three-way join problems.  Because of the
 
606
   exponential growth of the number of possibilities, this makes a big
 
607
   difference.  The planner tries to avoid getting stuck in huge join search
 
608
   problems by not collapsing a subquery if more than <varname>from_collapse_limit</>
 
609
   <literal>FROM</> items would result in the parent
 
610
   query.  You can trade off planning time against quality of plan by
 
611
   adjusting this run-time parameter up or down.
 
612
  </para>
 
613
 
 
614
  <para>
 
615
   <xref linkend="guc-from-collapse-limit"> and <xref
 
616
   linkend="guc-join-collapse-limit">
 
617
   are similarly named because they do almost the same thing: one controls
 
618
   when the planner will <quote>flatten out</> subselects, and the
 
619
   other controls when it will flatten out explicit inner joins.  Typically
 
620
   you would either set <varname>join_collapse_limit</> equal to
 
621
   <varname>from_collapse_limit</> (so that explicit joins and subselects
 
622
   act similarly) or set <varname>join_collapse_limit</> to 1 (if you want
 
623
   to control join order with explicit joins).  But you might set them
 
624
   differently if you are trying to fine-tune the trade off between planning
 
625
   time and run time.
 
626
  </para>
 
627
 </sect1>
 
628
 
 
629
 <sect1 id="populate">
 
630
  <title>Populating a Database</title>
 
631
 
 
632
  <para>
 
633
   One may need to insert a large amount of data when first populating
 
634
   a database. This section contains some suggestions on how to make
 
635
   this process as efficient as possible.
 
636
  </para>
 
637
 
 
638
  <sect2 id="disable-autocommit">
 
639
   <title>Disable Autocommit</title>
 
640
 
 
641
   <indexterm>
 
642
    <primary>autocommit</primary>
 
643
    <secondary>bulk-loading data</secondary>
 
644
   </indexterm>
 
645
 
 
646
   <para>
 
647
    Turn off autocommit and just do one commit at the end.  (In plain
 
648
    SQL, this means issuing <command>BEGIN</command> at the start and
 
649
    <command>COMMIT</command> at the end.  Some client libraries may
 
650
    do this behind your back, in which case you need to make sure the
 
651
    library does it when you want it done.)  If you allow each
 
652
    insertion to be committed separately,
 
653
    <productname>PostgreSQL</productname> is doing a lot of work for
 
654
    each row that is added.  An additional benefit of doing all
 
655
    insertions in one transaction is that if the insertion of one row
 
656
    were to fail then the insertion of all rows inserted up to that
 
657
    point would be rolled back, so you won't be stuck with partially
 
658
    loaded data.
 
659
   </para>
 
660
  </sect2>
 
661
 
 
662
  <sect2 id="populate-copy-from">
 
663
   <title>Use <command>COPY</command></title>
 
664
 
 
665
   <para>
 
666
    Use <xref linkend="sql-copy" endterm="sql-copy-title"> to load
 
667
    all the rows in one command, instead of using a series of
 
668
    <command>INSERT</command> commands.  The <command>COPY</command>
 
669
    command is optimized for loading large numbers of rows; it is less
 
670
    flexible than <command>INSERT</command>, but incurs significantly
 
671
    less overhead for large data loads. Since <command>COPY</command>
 
672
    is a single command, there is no need to disable autocommit if you
 
673
    use this method to populate a table.
 
674
   </para>
 
675
 
 
676
   <para>
 
677
    If you cannot use <command>COPY</command>, it may help to use <xref
 
678
    linkend="sql-prepare" endterm="sql-prepare-title"> to create a
 
679
    prepared <command>INSERT</command> statement, and then use
 
680
    <command>EXECUTE</command> as many times as required.  This avoids
 
681
    some of the overhead of repeatedly parsing and planning
 
682
    <command>INSERT</command>.
 
683
   </para>
 
684
 
 
685
   <para>
 
686
    Note that loading a large number of rows using
 
687
    <command>COPY</command> is almost always faster than using
 
688
    <command>INSERT</command>, even if <command>PREPARE</> is used and
 
689
    multiple insertions are batched into a single transaction.
 
690
   </para>
 
691
  </sect2>
 
692
 
 
693
  <sect2 id="populate-rm-indexes">
 
694
   <title>Remove Indexes</title>
 
695
 
 
696
   <para>
 
697
    If you are loading a freshly created table, the fastest way is to
 
698
    create the table, bulk load the table's data using
 
699
    <command>COPY</command>, then create any indexes needed for the
 
700
    table.  Creating an index on pre-existing data is quicker than
 
701
    updating it incrementally as each row is loaded.
 
702
   </para>
 
703
 
 
704
   <para>
 
705
    If you are augmenting an existing table, you can drop the index,
 
706
    load the table, and then recreate the index. Of course, the
 
707
    database performance for other users may be adversely affected
 
708
    during the time that the index is missing.  One should also think
 
709
    twice before dropping unique indexes, since the error checking
 
710
    afforded by the unique constraint will be lost while the index is
 
711
    missing.
 
712
   </para>
 
713
  </sect2>
 
714
 
 
715
  <sect2 id="populate-work-mem">
 
716
   <title>Increase <varname>maintenance_work_mem</varname></title>
 
717
 
 
718
   <para>
 
719
    Temporarily increasing the <xref linkend="guc-maintenance-work-mem">
 
720
    configuration variable when loading large amounts of data can
 
721
    lead to improved performance. This is because when a B-tree index
 
722
    is created from scratch, the existing content of the table needs
 
723
    to be sorted. Allowing the merge sort to use more memory
 
724
    means that fewer merge passes will be required.  A larger setting for
 
725
    <varname>maintenance_work_mem</varname> may also speed up validation
 
726
    of foreign-key constraints.
 
727
   </para>
 
728
  </sect2>
 
729
 
 
730
  <sect2 id="populate-checkpoint-segments">
 
731
   <title>Increase <varname>checkpoint_segments</varname></title>
 
732
 
 
733
   <para>
 
734
    Temporarily increasing the <xref
 
735
    linkend="guc-checkpoint-segments"> configuration variable can also
 
736
    make large data loads faster.  This is because loading a large
 
737
    amount of data into <productname>PostgreSQL</productname> can
 
738
    cause checkpoints to occur more often than the normal checkpoint
 
739
    frequency (specified by the <varname>checkpoint_timeout</varname>
 
740
    configuration variable). Whenever a checkpoint occurs, all dirty
 
741
    pages must be flushed to disk. By increasing
 
742
    <varname>checkpoint_segments</varname> temporarily during bulk
 
743
    data loads, the number of checkpoints that are required can be
 
744
    reduced.
 
745
   </para>
 
746
  </sect2>
 
747
 
 
748
  <sect2 id="populate-analyze">
 
749
   <title>Run <command>ANALYZE</command> Afterwards</title>
 
750
 
 
751
   <para>
 
752
    Whenever you have significantly altered the distribution of data
 
753
    within a table, running <xref linkend="sql-analyze"
 
754
    endterm="sql-analyze-title"> is strongly recommended. This
 
755
    includes bulk loading large amounts of data into the table.  Running
 
756
    <command>ANALYZE</command> (or <command>VACUUM ANALYZE</command>)
 
757
    ensures that the planner has up-to-date statistics about the
 
758
    table.  With no statistics or obsolete statistics, the planner may
 
759
    make poor decisions during query planning, leading to poor
 
760
    performance on any tables with inaccurate or nonexistent
 
761
    statistics.
 
762
   </para>
 
763
  </sect2>
 
764
  </sect1>
 
765
 
 
766
 </chapter>
 
767
 
 
768
<!-- Keep this comment at the end of the file
 
769
Local variables:
 
770
mode:sgml
 
771
sgml-omittag:nil
 
772
sgml-shorttag:t
 
773
sgml-minimize-attributes:nil
 
774
sgml-always-quote-attributes:t
 
775
sgml-indent-step:1
 
776
sgml-indent-data:t
 
777
sgml-parent-document:nil
 
778
sgml-default-dtd-file:"./reference.ced"
 
779
sgml-exposed-tags:nil
 
780
sgml-local-catalogs:("/usr/lib/sgml/catalog")
 
781
sgml-local-ecat-files:nil
 
782
End:
 
783
-->