OSDN Git Service

Make 'col IS NULL' clauses be indexable conditions.
[pg-rex/syncrep.git] / doc / src / sgml / ref / create_index.sgml
1 <!--
2 $PostgreSQL: pgsql/doc/src/sgml/ref/create_index.sgml,v 1.62 2007/04/06 22:33:41 tgl Exp $
3 PostgreSQL documentation
4 -->
5
6 <refentry id="SQL-CREATEINDEX">
7  <refmeta>
8   <refentrytitle id="sql-createindex-title">CREATE INDEX</refentrytitle>
9   <refmiscinfo>SQL - Language Statements</refmiscinfo>
10  </refmeta>
11
12  <refnamediv>
13   <refname>CREATE INDEX</refname>
14   <refpurpose>define a new index</refpurpose>
15  </refnamediv>
16
17  <indexterm zone="sql-createindex">
18   <primary>CREATE INDEX</primary>
19  </indexterm>
20
21  <refsynopsisdiv>
22 <synopsis>
23 CREATE [ UNIQUE ] INDEX [ CONCURRENTLY ] <replaceable class="parameter">name</replaceable> ON <replaceable class="parameter">table</replaceable> [ USING <replaceable class="parameter">method</replaceable> ]
24     ( { <replaceable class="parameter">column</replaceable> | ( <replaceable class="parameter">expression</replaceable> ) } [ <replaceable class="parameter">opclass</replaceable> ] [ ASC | DESC ] [ NULLS { FIRST | LAST } ] [, ...] )
25     [ WITH ( <replaceable class="PARAMETER">storage_parameter</replaceable> = <replaceable class="PARAMETER">value</replaceable> [, ... ] ) ]
26     [ TABLESPACE <replaceable class="parameter">tablespace</replaceable> ]
27     [ WHERE <replaceable class="parameter">predicate</replaceable> ]
28 </synopsis>
29  </refsynopsisdiv>
30
31  <refsect1>
32   <title>Description</title>
33
34   <para>
35    <command>CREATE INDEX</command> constructs an index <replaceable
36    class="parameter">index_name</replaceable> on the specified table.
37    Indexes are primarily used to enhance database performance (though
38    inappropriate use can result in slower performance).
39   </para>
40
41   <para>
42    The key field(s) for the index are specified as column names,
43    or alternatively as expressions written in parentheses.
44    Multiple fields can be specified if the index method supports
45    multicolumn indexes.
46   </para>
47
48   <para>
49    An index field can be an expression computed from the values of
50    one or more columns of the table row.  This feature can be used
51    to obtain fast access to data based on some transformation of
52    the basic data. For example, an index computed on
53    <literal>upper(col)</> would allow the clause
54    <literal>WHERE upper(col) = 'JIM'</> to use an index.
55   </para>
56
57   <para>
58    <productname>PostgreSQL</productname> provides the index methods
59    B-tree, hash, GiST, and GIN.  Users can also define their own index
60    methods, but that is fairly complicated.
61   </para>
62
63   <para>
64     When the <literal>WHERE</literal> clause is present, a
65     <firstterm>partial index</firstterm> is created.
66     A partial index is an index that contains entries for only a portion of
67     a table, usually a portion that is more useful for indexing than the
68     rest of the table. For example, if you have a table that contains both
69     billed and unbilled orders where the unbilled orders take up a small
70     fraction of the total table and yet that is an often used section, you
71     can improve performance by creating an index on just that portion.
72     Another possible application is to use <literal>WHERE</literal> with
73     <literal>UNIQUE</literal> to enforce uniqueness over a subset of a
74     table.  See <xref linkend="indexes-partial"> for more discussion.
75   </para>
76
77   <para>
78     The expression used in the <literal>WHERE</literal> clause can refer
79     only to columns of the underlying table, but it can use all columns,
80     not just the ones being indexed.  Presently, subqueries and
81     aggregate expressions are also forbidden in <literal>WHERE</literal>.
82     The same restrictions apply to index fields that are expressions.
83   </para>
84
85   <para>
86    All functions and operators used in an index definition must be
87    <quote>immutable</>, that is, their results must depend only on
88    their arguments and never on any outside influence (such as
89    the contents of another table or the current time).  This restriction
90    ensures that the behavior of the index is well-defined.  To use a
91    user-defined function in an index expression or <literal>WHERE</literal>
92    clause, remember to mark the function immutable when you create it.
93   </para>
94  </refsect1>
95
96  <refsect1>
97   <title>Parameters</title>
98
99     <variablelist>
100      <varlistentry>
101       <term><literal>UNIQUE</literal></term>
102       <listitem>
103        <para>
104         Causes the system to check for
105         duplicate values in the table when the index is created (if data
106         already exist) and each time data is added. Attempts to
107         insert or update data which would result in duplicate entries
108         will generate an error.
109        </para>
110       </listitem>
111      </varlistentry>
112
113      <varlistentry>
114       <term><literal>CONCURRENTLY</literal></term>
115       <listitem>
116        <para>
117         When this option is used, <productname>PostgreSQL</> will build the
118         index without taking any locks that prevent concurrent inserts,
119         updates, or deletes on the table; whereas a standard index build
120         locks out writes (but not reads) on the table until it's done.
121         There are several caveats to be aware of when using this option
122         &mdash; see <xref linkend="SQL-CREATEINDEX-CONCURRENTLY"
123         endterm="SQL-CREATEINDEX-CONCURRENTLY-title">.
124        </para>
125       </listitem>
126      </varlistentry>
127
128      <varlistentry>
129       <term><replaceable class="parameter">name</replaceable></term>
130       <listitem>
131        <para>
132         The name of the index to be created.  No schema name can be included
133         here; the index is always created in the same schema as its parent
134         table.
135        </para>
136       </listitem>
137      </varlistentry>
138
139      <varlistentry>
140       <term><replaceable class="parameter">table</replaceable></term>
141       <listitem>
142        <para>
143         The name (possibly schema-qualified) of the table to be indexed.
144        </para>
145       </listitem>
146      </varlistentry>
147
148      <varlistentry>
149       <term><replaceable class="parameter">method</replaceable></term>
150       <listitem>
151        <para>
152         The name of the index method to be used.  Choices are
153         <literal>btree</literal>, <literal>hash</literal>,
154         <literal>gist</literal>, and <literal>gin</>.  The
155         default method is <literal>btree</literal>.
156        </para>
157       </listitem>
158      </varlistentry>
159
160      <varlistentry>
161       <term><replaceable class="parameter">column</replaceable></term>
162       <listitem>
163        <para>
164         The name of a column of the table.
165        </para>
166       </listitem>
167      </varlistentry>
168
169      <varlistentry>
170       <term><replaceable class="parameter">expression</replaceable></term>
171       <listitem>
172        <para>
173         An expression based on one or more columns of the table.  The
174         expression usually must be written with surrounding parentheses,
175         as shown in the syntax.  However, the parentheses can be omitted
176         if the expression has the form of a function call.
177        </para>
178       </listitem>
179      </varlistentry>
180
181      <varlistentry>
182       <term><replaceable class="parameter">opclass</replaceable></term>
183       <listitem>
184        <para>
185         The name of an operator class. See below for details.
186        </para>
187       </listitem>
188      </varlistentry>
189
190      <varlistentry>
191       <term><literal>ASC</></term>
192       <listitem>
193        <para>
194         Specifies ascending sort order (which is the default).
195        </para>
196       </listitem>
197      </varlistentry>
198
199      <varlistentry>
200       <term><literal>DESC</></term>
201       <listitem>
202        <para>
203         Specifies descending sort order.
204        </para>
205       </listitem>
206      </varlistentry>
207
208      <varlistentry>
209       <term><literal>NULLS FIRST</></term>
210       <listitem>
211        <para>
212         Specifies that nulls sort before non-nulls.  This is the default
213         when <literal>DESC</> is specified.
214        </para>
215       </listitem>
216      </varlistentry>
217
218      <varlistentry>
219       <term><literal>NULLS LAST</></term>
220       <listitem>
221        <para>
222         Specifies that nulls sort after non-nulls.  This is the default
223         when <literal>DESC</> is not specified.
224        </para>
225       </listitem>
226      </varlistentry>
227
228      <varlistentry>
229       <term><replaceable class="parameter">storage_parameter</replaceable></term>
230       <listitem>
231        <para>
232         The name of an index-method-specific storage parameter.  See
233         below for details.
234        </para>
235       </listitem>
236      </varlistentry>
237
238      <varlistentry>
239       <term><replaceable class="parameter">tablespace</replaceable></term>
240       <listitem>
241        <para>
242         The tablespace in which to create the index.  If not specified,
243         <xref linkend="guc-default-tablespace"> is used, or the database's
244         default tablespace if <varname>default_tablespace</> is an empty
245         string.
246        </para>
247       </listitem>
248      </varlistentry>
249
250      <varlistentry>
251       <term><replaceable class="parameter">predicate</replaceable></term>
252       <listitem>
253        <para>
254         The constraint expression for a partial index.
255        </para>
256       </listitem>
257      </varlistentry>
258
259     </variablelist>
260
261   <refsect2 id="SQL-CREATEINDEX-storage-parameters">
262    <title id="SQL-CREATEINDEX-storage-parameters-title">Index Storage Parameters</title>
263
264    <para>
265     The <literal>WITH</> clause can specify <firstterm>storage parameters</>
266     for indexes.  Each index method can have its own set of allowed storage
267     parameters.  The built-in index methods all accept a single parameter:
268    </para>
269
270    <variablelist>
271
272    <varlistentry>
273     <term><literal>FILLFACTOR</></term>
274     <listitem>
275      <para>
276       The fillfactor for an index is a percentage that determines how full
277       the index method will try to pack index pages.  For B-trees, leaf pages
278       are filled to this percentage during initial index build, and also
279       when extending the index at the right (largest key values).  If pages
280       subsequently become completely full, they will be split, leading to
281       gradual degradation in the index's efficiency.  B-trees use a default
282       fillfactor of 90, but any value from 10 to 100 can be selected.
283       If the table is static then fillfactor 100 is best to minimize the
284       index's physical size, but for heavily updated tables a smaller
285       fillfactor is better to minimize the need for page splits.  The
286       other index methods use fillfactor in different but roughly analogous
287       ways; the default fillfactor varies between methods.
288      </para>
289     </listitem>
290    </varlistentry>
291
292    </variablelist>
293
294   </refsect2>
295
296   <refsect2 id="SQL-CREATEINDEX-CONCURRENTLY">
297    <title id="SQL-CREATEINDEX-CONCURRENTLY-title">Building Indexes Concurrently</title>
298
299    <indexterm zone="SQL-CREATEINDEX-CONCURRENTLY">
300    <primary>index</primary>
301    <secondary>building concurrently</secondary>
302    </indexterm>
303
304    <para>
305     Creating an index can interfere with regular operation of a database.
306     Normally <productname>PostgreSQL</> locks the table to be indexed against
307     writes and performs the entire index build with a single scan of the
308     table. Other transactions can still read the table, but if they try to
309     insert, update, or delete rows in the table they will block until the
310     index build is finished. This could have a severe effect if the system is
311     a live production database. Large tables can take many hours to be
312     indexed, and even for smaller tables, an index build can lock out writers
313     for periods that are unacceptably long for a production system.
314    </para>
315
316    <para>
317     <productname>PostgreSQL</> supports building indexes without locking
318     out writes.  This method is invoked by specifying the
319     <literal>CONCURRENTLY</> option of <command>CREATE INDEX</>.
320     When this option is used,
321     <productname>PostgreSQL</> must perform two scans of the table, and in
322     addition it must wait for all existing transactions to terminate.  Thus
323     this method requires more total work than a standard index build and takes
324     significantly longer to complete.  However, since it allows normal
325     operations to continue while the index is built, this method is useful for
326     adding new indexes in a production environment.  Of course, the extra CPU
327     and I/O load imposed by the index creation might slow other operations.
328    </para>
329
330    <para>
331     If a problem arises during the second scan of the table, such as a
332     uniqueness violation in a unique index, the <command>CREATE INDEX</>
333     command will fail but leave behind an <quote>invalid</> index. This index
334     will be ignored for querying purposes because it might be incomplete;
335     however it will still consume update overhead. The <application>psql</>
336     <command>\d</> command will mark such an index as <literal>INVALID</>:
337
338 <programlisting>
339 postgres=# \d tab
340        Table "public.tab"
341  Column |  Type   | Modifiers 
342 --------+---------+-----------
343  col    | integer | 
344 Indexes:
345     "idx" btree (col) INVALID
346 </programlisting>
347
348     The recommended recovery
349     method in such cases is to drop the index and try again to perform
350     <command>CREATE INDEX CONCURRENTLY</>.  (Another possibility is to rebuild
351     the index with <command>REINDEX</>.  However, since <command>REINDEX</>
352     does not support concurrent builds, this option is unlikely to seem
353     attractive.)
354    </para>
355
356    <para>
357     Another caveat when building a unique index concurrently is that the
358     uniqueness constraint is already being enforced against other transactions
359     when the second table scan begins.  This means that constraint violations
360     could be reported in other queries prior to the index becoming available
361     for use, or even in cases where the index build eventually fails.  Also,
362     if a failure does occur in the second scan, the <quote>invalid</> index
363     continues to enforce its uniqueness constraint afterwards.
364    </para>
365
366    <para>
367     Concurrent builds of expression indexes and partial indexes are supported.
368     Errors occurring in the evaluation of these expressions could cause
369     behavior similar to that described above for unique constraint violations.
370    </para>
371
372    <para>
373     Regular index builds permit other regular index builds on the
374     same table to occur in parallel, but only one concurrent index build
375     can occur on a table at a time.  In both cases, no other types of schema
376     modification on the table are allowed meanwhile.  Another difference
377     is that a regular <command>CREATE INDEX</> command can be performed within
378     a transaction block, but <command>CREATE INDEX CONCURRENTLY</> cannot.
379    </para>
380   </refsect2>
381  </refsect1>
382
383  <refsect1>
384   <title>Notes</title>
385
386   <para>
387    See <xref linkend="indexes"> for information about when indexes can
388    be used, when they are not used, and in which particular situations
389    they can be useful.
390   </para>
391
392   <para>
393    Currently, only the B-tree and GiST index methods support
394    multicolumn indexes. Up to 32 fields can be specified by default.
395    (This limit can be altered when building
396    <productname>PostgreSQL</productname>.)  Only B-tree currently
397    supports unique indexes.
398   </para>
399
400   <para>
401    An <firstterm>operator class</firstterm> can be specified for each
402    column of an index. The operator class identifies the operators to be
403    used by the index for that column. For example, a B-tree index on
404    four-byte integers would use the <literal>int4_ops</literal> class;
405    this operator class includes comparison functions for four-byte
406    integers. In practice the default operator class for the column's data
407    type is usually sufficient. The main point of having operator classes
408    is that for some data types, there could be more than one meaningful
409    ordering. For example, we might want to sort a complex-number data
410    type either by absolute value or by real part. We could do this by
411    defining two operator classes for the data type and then selecting
412    the proper class when making an index.  More information about
413    operator classes is in <xref linkend="indexes-opclass"> and in <xref
414    linkend="xindex">.
415   </para>
416
417   <para>
418    For index methods that support ordered scans (currently, only B-tree),
419    the optional clauses <literal>ASC</>, <literal>DESC</>, <literal>NULLS
420    FIRST</>, and/or <literal>NULLS LAST</> can be specified to reverse
421    the normal sort direction of the index.  Since an ordered index can be
422    scanned either forward or backward, it is not normally useful to create a 
423    single-column <literal>DESC</> index &mdash; that sort ordering is already
424    available with a regular index.  The value of these options is that
425    multicolumn indexes can be created that match the sort ordering requested
426    by a mixed-ordering query, such as <literal>SELECT ... ORDER BY x ASC, y
427    DESC</>.  The <literal>NULLS</> options are useful if you need to support
428    <quote>nulls sort low</> behavior, rather than the default <quote>nulls
429    sort high</>, in queries that depend on indexes to avoid sorting steps.
430   </para>
431
432   <para>
433    Use <xref linkend="sql-dropindex" endterm="sql-dropindex-title">
434    to remove an index.
435   </para>
436
437   <para>
438    Prior releases of <productname>PostgreSQL</productname> also had an
439    R-tree index method.  This method has been removed because
440    it had no significant advantages over the GiST method.
441    If <literal>USING rtree</> is specified, <command>CREATE INDEX</>
442    will interpret it as <literal>USING gist</>, to simplify conversion
443    of old databases to GiST.
444   </para>
445  </refsect1>
446
447  <refsect1>
448   <title>Examples</title>
449
450   <para>
451    To create a B-tree index on the column <literal>title</literal> in
452    the table <literal>films</literal>:
453 <programlisting>
454 CREATE UNIQUE INDEX title_idx ON films (title);
455 </programlisting>
456   </para>
457
458   <para>
459    To create an index on the expression <literal>lower(title)</>,
460    allowing efficient case-insensitive searches:
461 <programlisting>
462 CREATE INDEX lower_title_idx ON films ((lower(title)));
463 </programlisting>
464   </para>
465
466   <para>
467    To create an index with non-default sort ordering of nulls:
468 <programlisting>
469 CREATE INDEX title_idx_nulls_low ON films (title NULLS FIRST);
470 </programlisting>
471   </para>
472
473   <para>
474    To create an index with non-default fill factor:
475 <programlisting>
476 CREATE UNIQUE INDEX title_idx ON films (title) WITH (fillfactor = 70);
477 </programlisting>
478   </para>
479
480   <para>
481    To create an index on the column <literal>code</> in the table
482    <literal>films</> and have the index reside in the tablespace
483    <literal>indexspace</>:
484 <programlisting>
485 CREATE INDEX code_idx ON films(code) TABLESPACE indexspace;
486 </programlisting>
487   </para>
488
489 <!--
490 <comment>
491 Is this example correct?
492 </comment>
493   <para>
494    To create a GiST index on a point attribute so that we
495    can efficiently use box operators on the result of the
496    conversion function:
497   <programlisting>
498 CREATE INDEX pointloc
499     ON points USING GIST (point2box(location) box_ops);
500 SELECT * FROM points
501     WHERE point2box(points.pointloc) = boxes.box;
502   </programlisting>
503   </para>
504 -->
505
506   <para>
507    To create an index without locking out writes to the table:
508 <programlisting>
509 CREATE INDEX CONCURRENTLY sales_quantity_index ON sales_table (quantity);
510 </programlisting>
511   </para>
512
513  </refsect1>
514
515  <refsect1>
516   <title>Compatibility</title>
517
518   <para>
519    <command>CREATE INDEX</command> is a
520    <productname>PostgreSQL</productname> language extension.  There
521    are no provisions for indexes in the SQL standard.
522   </para>
523  </refsect1>
524
525  <refsect1>
526   <title>See Also</title>
527
528   <simplelist type="inline">
529    <member><xref linkend="sql-alterindex" endterm="sql-alterindex-title"></member>
530    <member><xref linkend="sql-dropindex" endterm="sql-dropindex-title"></member>
531   </simplelist>
532  </refsect1>
533 </refentry>