2 $PostgreSQL: pgsql/doc/src/sgml/ref/create_index.sgml,v 1.69 2008/11/14 10:22:46 petere Exp $
3 PostgreSQL documentation
6 <refentry id="SQL-CREATEINDEX">
8 <refentrytitle id="sql-createindex-title">CREATE INDEX</refentrytitle>
9 <manvolnum>7</manvolnum>
10 <refmiscinfo>SQL - Language Statements</refmiscinfo>
14 <refname>CREATE INDEX</refname>
15 <refpurpose>define a new index</refpurpose>
18 <indexterm zone="sql-createindex">
19 <primary>CREATE INDEX</primary>
24 CREATE [ UNIQUE ] INDEX [ CONCURRENTLY ] <replaceable class="parameter">name</replaceable> ON <replaceable class="parameter">table</replaceable> [ USING <replaceable class="parameter">method</replaceable> ]
25 ( { <replaceable class="parameter">column</replaceable> | ( <replaceable class="parameter">expression</replaceable> ) } [ <replaceable class="parameter">opclass</replaceable> ] [ ASC | DESC ] [ NULLS { FIRST | LAST } ] [, ...] )
26 [ WITH ( <replaceable class="PARAMETER">storage_parameter</replaceable> = <replaceable class="PARAMETER">value</replaceable> [, ... ] ) ]
27 [ TABLESPACE <replaceable class="parameter">tablespace</replaceable> ]
28 [ WHERE <replaceable class="parameter">predicate</replaceable> ]
33 <title>Description</title>
36 <command>CREATE INDEX</command> constructs an index named <replaceable
37 class="parameter">name</replaceable> on the specified table.
38 Indexes are primarily used to enhance database performance (though
39 inappropriate use can result in slower performance).
43 The key field(s) for the index are specified as column names,
44 or alternatively as expressions written in parentheses.
45 Multiple fields can be specified if the index method supports
50 An index field can be an expression computed from the values of
51 one or more columns of the table row. This feature can be used
52 to obtain fast access to data based on some transformation of
53 the basic data. For example, an index computed on
54 <literal>upper(col)</> would allow the clause
55 <literal>WHERE upper(col) = 'JIM'</> to use an index.
59 <productname>PostgreSQL</productname> provides the index methods
60 B-tree, hash, GiST, and GIN. Users can also define their own index
61 methods, but that is fairly complicated.
65 When the <literal>WHERE</literal> clause is present, a
66 <firstterm>partial index</firstterm> is created.
67 A partial index is an index that contains entries for only a portion of
68 a table, usually a portion that is more useful for indexing than the
69 rest of the table. For example, if you have a table that contains both
70 billed and unbilled orders where the unbilled orders take up a small
71 fraction of the total table and yet that is an often used section, you
72 can improve performance by creating an index on just that portion.
73 Another possible application is to use <literal>WHERE</literal> with
74 <literal>UNIQUE</literal> to enforce uniqueness over a subset of a
75 table. See <xref linkend="indexes-partial"> for more discussion.
79 The expression used in the <literal>WHERE</literal> clause can refer
80 only to columns of the underlying table, but it can use all columns,
81 not just the ones being indexed. Presently, subqueries and
82 aggregate expressions are also forbidden in <literal>WHERE</literal>.
83 The same restrictions apply to index fields that are expressions.
87 All functions and operators used in an index definition must be
88 <quote>immutable</>, that is, their results must depend only on
89 their arguments and never on any outside influence (such as
90 the contents of another table or the current time). This restriction
91 ensures that the behavior of the index is well-defined. To use a
92 user-defined function in an index expression or <literal>WHERE</literal>
93 clause, remember to mark the function immutable when you create it.
98 <title>Parameters</title>
102 <term><literal>UNIQUE</literal></term>
105 Causes the system to check for
106 duplicate values in the table when the index is created (if data
107 already exist) and each time data is added. Attempts to
108 insert or update data which would result in duplicate entries
109 will generate an error.
115 <term><literal>CONCURRENTLY</literal></term>
118 When this option is used, <productname>PostgreSQL</> will build the
119 index without taking any locks that prevent concurrent inserts,
120 updates, or deletes on the table; whereas a standard index build
121 locks out writes (but not reads) on the table until it's done.
122 There are several caveats to be aware of when using this option
123 — see <xref linkend="SQL-CREATEINDEX-CONCURRENTLY"
124 endterm="SQL-CREATEINDEX-CONCURRENTLY-title">.
130 <term><replaceable class="parameter">name</replaceable></term>
133 The name of the index to be created. No schema name can be included
134 here; the index is always created in the same schema as its parent
141 <term><replaceable class="parameter">table</replaceable></term>
144 The name (possibly schema-qualified) of the table to be indexed.
150 <term><replaceable class="parameter">method</replaceable></term>
153 The name of the index method to be used. Choices are
154 <literal>btree</literal>, <literal>hash</literal>,
155 <literal>gist</literal>, and <literal>gin</>. The
156 default method is <literal>btree</literal>.
162 <term><replaceable class="parameter">column</replaceable></term>
165 The name of a column of the table.
171 <term><replaceable class="parameter">expression</replaceable></term>
174 An expression based on one or more columns of the table. The
175 expression usually must be written with surrounding parentheses,
176 as shown in the syntax. However, the parentheses can be omitted
177 if the expression has the form of a function call.
183 <term><replaceable class="parameter">opclass</replaceable></term>
186 The name of an operator class. See below for details.
192 <term><literal>ASC</></term>
195 Specifies ascending sort order (which is the default).
201 <term><literal>DESC</></term>
204 Specifies descending sort order.
210 <term><literal>NULLS FIRST</></term>
213 Specifies that nulls sort before non-nulls. This is the default
214 when <literal>DESC</> is specified.
220 <term><literal>NULLS LAST</></term>
223 Specifies that nulls sort after non-nulls. This is the default
224 when <literal>DESC</> is not specified.
230 <term><replaceable class="parameter">storage_parameter</replaceable></term>
233 The name of an index-method-specific storage parameter. See
240 <term><replaceable class="parameter">tablespace</replaceable></term>
243 The tablespace in which to create the index. If not specified,
244 <xref linkend="guc-default-tablespace"> is consulted, or
245 <xref linkend="guc-temp-tablespaces"> for indexes on temporary
252 <term><replaceable class="parameter">predicate</replaceable></term>
255 The constraint expression for a partial index.
262 <refsect2 id="SQL-CREATEINDEX-storage-parameters">
263 <title id="SQL-CREATEINDEX-storage-parameters-title">Index Storage Parameters</title>
266 The <literal>WITH</> clause can specify <firstterm>storage parameters</>
267 for indexes. Each index method can have its own set of allowed storage
268 parameters. The built-in index methods all accept a single parameter:
274 <term><literal>FILLFACTOR</></term>
277 The fillfactor for an index is a percentage that determines how full
278 the index method will try to pack index pages. For B-trees, leaf pages
279 are filled to this percentage during initial index build, and also
280 when extending the index at the right (largest key values). If pages
281 subsequently become completely full, they will be split, leading to
282 gradual degradation in the index's efficiency. B-trees use a default
283 fillfactor of 90, but any value from 10 to 100 can be selected.
284 If the table is static then fillfactor 100 is best to minimize the
285 index's physical size, but for heavily updated tables a smaller
286 fillfactor is better to minimize the need for page splits. The
287 other index methods use fillfactor in different but roughly analogous
288 ways; the default fillfactor varies between methods.
297 <refsect2 id="SQL-CREATEINDEX-CONCURRENTLY">
298 <title id="SQL-CREATEINDEX-CONCURRENTLY-title">Building Indexes Concurrently</title>
300 <indexterm zone="SQL-CREATEINDEX-CONCURRENTLY">
301 <primary>index</primary>
302 <secondary>building concurrently</secondary>
306 Creating an index can interfere with regular operation of a database.
307 Normally <productname>PostgreSQL</> locks the table to be indexed against
308 writes and performs the entire index build with a single scan of the
309 table. Other transactions can still read the table, but if they try to
310 insert, update, or delete rows in the table they will block until the
311 index build is finished. This could have a severe effect if the system is
312 a live production database. Very large tables can take many hours to be
313 indexed, and even for smaller tables, an index build can lock out writers
314 for periods that are unacceptably long for a production system.
318 <productname>PostgreSQL</> supports building indexes without locking
319 out writes. This method is invoked by specifying the
320 <literal>CONCURRENTLY</> option of <command>CREATE INDEX</>.
321 When this option is used,
322 <productname>PostgreSQL</> must perform two scans of the table, and in
323 addition it must wait for all existing transactions that could potentially
324 use the index to terminate. Thus
325 this method requires more total work than a standard index build and takes
326 significantly longer to complete. However, since it allows normal
327 operations to continue while the index is built, this method is useful for
328 adding new indexes in a production environment. Of course, the extra CPU
329 and I/O load imposed by the index creation might slow other operations.
333 In a concurrent index build, the index is actually entered into the
334 system catalogs in one transaction, then the two table scans occur in a
335 second and third transaction.
336 If a problem arises while scanning the table, such as a
337 uniqueness violation in a unique index, the <command>CREATE INDEX</>
338 command will fail but leave behind an <quote>invalid</> index. This index
339 will be ignored for querying purposes because it might be incomplete;
340 however it will still consume update overhead. The <application>psql</>
341 <command>\d</> command will mark such an index as <literal>INVALID</>:
346 Column | Type | Modifiers
347 --------+---------+-----------
350 "idx" btree (col) INVALID
353 The recommended recovery
354 method in such cases is to drop the index and try again to perform
355 <command>CREATE INDEX CONCURRENTLY</>. (Another possibility is to rebuild
356 the index with <command>REINDEX</>. However, since <command>REINDEX</>
357 does not support concurrent builds, this option is unlikely to seem
362 Another caveat when building a unique index concurrently is that the
363 uniqueness constraint is already being enforced against other transactions
364 when the second table scan begins. This means that constraint violations
365 could be reported in other queries prior to the index becoming available
366 for use, or even in cases where the index build eventually fails. Also,
367 if a failure does occur in the second scan, the <quote>invalid</> index
368 continues to enforce its uniqueness constraint afterwards.
372 Concurrent builds of expression indexes and partial indexes are supported.
373 Errors occurring in the evaluation of these expressions could cause
374 behavior similar to that described above for unique constraint violations.
378 Regular index builds permit other regular index builds on the
379 same table to occur in parallel, but only one concurrent index build
380 can occur on a table at a time. In both cases, no other types of schema
381 modification on the table are allowed meanwhile. Another difference
382 is that a regular <command>CREATE INDEX</> command can be performed within
383 a transaction block, but <command>CREATE INDEX CONCURRENTLY</> cannot.
392 See <xref linkend="indexes"> for information about when indexes can
393 be used, when they are not used, and in which particular situations
398 Currently, only the B-tree, GiST and GIN index methods support
399 multicolumn indexes. Up to 32 fields can be specified by default.
400 (This limit can be altered when building
401 <productname>PostgreSQL</productname>.) Only B-tree currently
402 supports unique indexes.
406 An <firstterm>operator class</firstterm> can be specified for each
407 column of an index. The operator class identifies the operators to be
408 used by the index for that column. For example, a B-tree index on
409 four-byte integers would use the <literal>int4_ops</literal> class;
410 this operator class includes comparison functions for four-byte
411 integers. In practice the default operator class for the column's data
412 type is usually sufficient. The main point of having operator classes
413 is that for some data types, there could be more than one meaningful
414 ordering. For example, we might want to sort a complex-number data
415 type either by absolute value or by real part. We could do this by
416 defining two operator classes for the data type and then selecting
417 the proper class when making an index. More information about
418 operator classes is in <xref linkend="indexes-opclass"> and in <xref
423 For index methods that support ordered scans (currently, only B-tree),
424 the optional clauses <literal>ASC</>, <literal>DESC</>, <literal>NULLS
425 FIRST</>, and/or <literal>NULLS LAST</> can be specified to reverse
426 the normal sort direction of the index. Since an ordered index can be
427 scanned either forward or backward, it is not normally useful to create a
428 single-column <literal>DESC</> index — that sort ordering is already
429 available with a regular index. The value of these options is that
430 multicolumn indexes can be created that match the sort ordering requested
431 by a mixed-ordering query, such as <literal>SELECT ... ORDER BY x ASC, y
432 DESC</>. The <literal>NULLS</> options are useful if you need to support
433 <quote>nulls sort low</> behavior, rather than the default <quote>nulls
434 sort high</>, in queries that depend on indexes to avoid sorting steps.
438 For most index methods, the speed of creating an index is
439 dependent on the setting of <xref linkend="guc-maintenance-work-mem">.
440 Larger values will reduce the time needed for index creation, so long
441 as you don't make it larger than the amount of memory really available,
442 which would drive the machine into swapping. For hash indexes, the
443 value of <xref linkend="guc-effective-cache-size"> is also relevant to
444 index creation time: <productname>PostgreSQL</productname> will use one
445 of two different hash index creation methods depending on whether the
446 estimated index size is more or less than <varname>effective_cache_size</>.
447 For best results, make sure that this parameter is also set to something
448 reflective of available memory, and be careful that the sum of
449 <varname>maintenance_work_mem</> and <varname>effective_cache_size</> is
450 less than the machine's RAM less whatever space is needed by other
455 Use <xref linkend="sql-dropindex" endterm="sql-dropindex-title">
460 Prior releases of <productname>PostgreSQL</productname> also had an
461 R-tree index method. This method has been removed because
462 it had no significant advantages over the GiST method.
463 If <literal>USING rtree</> is specified, <command>CREATE INDEX</>
464 will interpret it as <literal>USING gist</>, to simplify conversion
465 of old databases to GiST.
470 <title>Examples</title>
473 To create a B-tree index on the column <literal>title</literal> in
474 the table <literal>films</literal>:
476 CREATE UNIQUE INDEX title_idx ON films (title);
481 To create an index on the expression <literal>lower(title)</>,
482 allowing efficient case-insensitive searches:
484 CREATE INDEX lower_title_idx ON films ((lower(title)));
489 To create an index with non-default sort ordering of nulls:
491 CREATE INDEX title_idx_nulls_low ON films (title NULLS FIRST);
496 To create an index with non-default fill factor:
498 CREATE UNIQUE INDEX title_idx ON films (title) WITH (fillfactor = 70);
503 To create an index on the column <literal>code</> in the table
504 <literal>films</> and have the index reside in the tablespace
505 <literal>indexspace</>:
507 CREATE INDEX code_idx ON films(code) TABLESPACE indexspace;
513 Is this example correct?
516 To create a GiST index on a point attribute so that we
517 can efficiently use box operators on the result of the
520 CREATE INDEX pointloc
521 ON points USING GIST (point2box(location) box_ops);
523 WHERE point2box(points.pointloc) = boxes.box;
529 To create an index without locking out writes to the table:
531 CREATE INDEX CONCURRENTLY sales_quantity_index ON sales_table (quantity);
538 <title>Compatibility</title>
541 <command>CREATE INDEX</command> is a
542 <productname>PostgreSQL</productname> language extension. There
543 are no provisions for indexes in the SQL standard.
548 <title>See Also</title>
550 <simplelist type="inline">
551 <member><xref linkend="sql-alterindex" endterm="sql-alterindex-title"></member>
552 <member><xref linkend="sql-dropindex" endterm="sql-dropindex-title"></member>