2
$PostgreSQL: pgsql/doc/src/sgml/perform.sgml,v 1.49 2004-12-23 23:07:38 tgl Exp $
5
<chapter id="performance-tips">
6
<title>Performance Tips</title>
8
<indexterm zone="performance-tips">
9
<primary>performance</primary>
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.
19
<sect1 id="using-explain">
20
<title>Using <command>EXPLAIN</command></title>
22
<indexterm zone="using-explain">
23
<primary>EXPLAIN</primary>
26
<indexterm zone="using-explain">
27
<primary>query plan</primary>
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.
42
The numbers that are currently quoted by <command>EXPLAIN</command> are:
47
Estimated start-up cost (Time expended before output scan can start,
48
e.g., time to do the sorting in a sort node.)
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,
62
Estimated number of rows output by this plan node (Again, only if
63
executed to completion)
69
Estimated average width (in bytes) of rows output by this plan
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">.)
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.)
96
Rows output is a little tricky because it is <emphasis>not</emphasis> the
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
106
Here are some examples (using the regression test database after a
107
<command>VACUUM ANALYZE</>, and 7.3 development sources):
110
EXPLAIN SELECT * FROM tenk1;
113
-------------------------------------------------------------
114
Seq Scan on tenk1 (cost=0.00..333.00 rows=10000 width=148)
119
This is about as straightforward as it gets. If you do
122
SELECT * FROM pg_class WHERE relname = 'tenk1';
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>).
133
Now let's modify the query to add a <literal>WHERE</> condition:
136
EXPLAIN SELECT * FROM tenk1 WHERE unique1 < 1000;
139
------------------------------------------------------------
140
Seq Scan on tenk1 (cost=0.00..358.00 rows=1033 width=148)
141
Filter: (unique1 < 1000)
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.
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.
160
Modify the query to restrict the condition even more:
163
EXPLAIN SELECT * FROM tenk1 WHERE unique1 < 50;
166
-------------------------------------------------------------------------------
167
Index Scan using tenk1_unique1 on tenk1 (cost=0.00..179.33 rows=49 width=148)
168
Index Cond: (unique1 < 50)
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.
180
Add another condition to the <literal>WHERE</> clause:
183
EXPLAIN SELECT * FROM tenk1 WHERE unique1 < 50 AND stringu1 = 'xxx';
186
-------------------------------------------------------------------------------
187
Index Scan using tenk1_unique1 on tenk1 (cost=0.00..179.45 rows=1 width=148)
188
Index Cond: (unique1 < 50)
189
Filter: (stringu1 = 'xxx'::name)
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.
202
Let's try joining two tables, using the columns we have been discussing:
205
EXPLAIN SELECT * FROM tenk1 t1, tenk2 t2 WHERE t1.unique1 < 50 AND t1.unique2 = t2.unique2;
208
----------------------------------------------------------------------------
209
Nested Loop (cost=0.00..327.02 rows=49 width=296)
210
-> Index Scan using tenk1_unique1 on tenk1 t1
211
(cost=0.00..179.33 rows=49 width=148)
212
Index Cond: (unique1 < 50)
213
-> 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)
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 < 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
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.
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 < t2.hundred</literal>,
242
that would decrease the output row count of the join node, but not change
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">.)
253
SET enable_nestloop = off;
254
EXPLAIN SELECT * FROM tenk1 t1, tenk2 t2 WHERE t1.unique1 < 50 AND t1.unique2 = t2.unique2;
257
--------------------------------------------------------------------------
258
Hash Join (cost=179.45..563.06 rows=49 width=296)
259
Hash Cond: ("outer".unique2 = "inner".unique2)
260
-> Seq Scan on tenk2 t2 (cost=0.00..333.00 rows=10000 width=148)
261
-> Hash (cost=179.33..179.33 rows=49 width=148)
262
-> Index Scan using tenk1_unique1 on tenk1 t1
263
(cost=0.00..179.33 rows=49 width=148)
264
Index Cond: (unique1 < 50)
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.
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:
287
EXPLAIN ANALYZE SELECT * FROM tenk1 t1, tenk2 t2 WHERE t1.unique1 < 50 AND t1.unique2 = t2.unique2;
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
-> 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 < 50)
297
-> 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
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.
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
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.
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.
349
<sect1 id="planner-stats">
350
<title>Statistics Used by the Planner</title>
352
<indexterm zone="planner-stats">
353
<primary>statistics</primary>
354
<secondary>of the planner</secondary>
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.
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:
373
SELECT relname, relkind, reltuples, relpages FROM pg_class WHERE relname LIKE 'tenk1%';
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
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.
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
404
<primary>pg_statistic</primary>
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.
420
<primary>pg_stats</primary>
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:
437
SELECT attname, n_distinct, most_common_vals FROM pg_stats WHERE tablename = 'road';
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)]"}
448
<structname>pg_stats</structname> is described in detail in
449
<xref linkend="view-pg-stats">.
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.
470
<sect1 id="explicit-joins">
471
<title>Controlling the Planner with Explicit <literal>JOIN</> Clauses</title>
473
<indexterm zone="explicit-joins">
474
<primary>join</primary>
475
<secondary>controlling the order</secondary>
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.
485
In a simple join query, such as
487
SELECT * FROM a, b, c WHERE a.id = b.id AND b.ref = c.id;
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.
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
519
The genetic search takes less time, but it won't
520
necessarily find the best possible plan.
524
When the query involves outer joins, the planner has much less freedom
525
than it does for plain (inner) joins. For example, consider
527
SELECT * FROM a LEFT JOIN (b JOIN c ON (b.ref = c.id)) ON (a.id = b.id);
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.
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:
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);
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.
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.)
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
567
SELECT * FROM a CROSS JOIN b, c, d, e WHERE ...;
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.
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
— assuming that you know of a better order, that is. Experimentation
585
A closely related issue that affects planning time is collapsing of
586
subqueries into their parent query. For example, consider
590
(SELECT * FROM a, b, c WHERE something) AS ss
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
598
SELECT * FROM x, y, a, b, c WHERE something AND somethingelse;
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.
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
629
<sect1 id="populate">
630
<title>Populating a Database</title>
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.
638
<sect2 id="disable-autocommit">
639
<title>Disable Autocommit</title>
642
<primary>autocommit</primary>
643
<secondary>bulk-loading data</secondary>
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
662
<sect2 id="populate-copy-from">
663
<title>Use <command>COPY</command></title>
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.
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>.
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.
693
<sect2 id="populate-rm-indexes">
694
<title>Remove Indexes</title>
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.
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
715
<sect2 id="populate-work-mem">
716
<title>Increase <varname>maintenance_work_mem</varname></title>
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.
730
<sect2 id="populate-checkpoint-segments">
731
<title>Increase <varname>checkpoint_segments</varname></title>
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
748
<sect2 id="populate-analyze">
749
<title>Run <command>ANALYZE</command> Afterwards</title>
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
768
<!-- Keep this comment at the end of the file
773
sgml-minimize-attributes:nil
774
sgml-always-quote-attributes: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