codekingpro/portable-devtools
115k
1<?xml version="1.0" encoding="UTF-8" standalone="no"?>2<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>CREATE INDEX</title><link rel="stylesheet" type="text/css" href="stylesheet.css" /><link rev="made" href="pgsql-docs@lists.postgresql.org" /><meta name="generator" content="DocBook XSL Stylesheets Vsnapshot" /><link rel="prev" href="sql-creategroup.html" title="CREATE GROUP" /><link rel="next" href="sql-createlanguage.html" title="CREATE LANGUAGE" /></head><body id="docContent" class="container-fluid col-10"><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="5" align="center">CREATE INDEX</th></tr><tr><td width="10%" align="left"><a accesskey="p" href="sql-creategroup.html" title="CREATE GROUP">Prev</a> </td><td width="10%" align="left"><a accesskey="u" href="sql-commands.html" title="SQL Commands">Up</a></td><th width="60%" align="center">SQL Commands</th><td width="10%" align="right"><a accesskey="h" href="index.html" title="PostgreSQL 16.3 Documentation">Home</a></td><td width="10%" align="right"> <a accesskey="n" href="sql-createlanguage.html" title="CREATE LANGUAGE">Next</a></td></tr></table><hr /></div><div class="refentry" id="SQL-CREATEINDEX"><div class="titlepage"></div><a id="id-1.9.3.69.1" class="indexterm"></a><div class="refnamediv"><h2><span class="refentrytitle">CREATE INDEX</span></h2><p>CREATE INDEX — define a new index</p></div><div class="refsynopsisdiv"><h2>Synopsis</h2><pre class="synopsis">3CREATE [ UNIQUE ] INDEX [ CONCURRENTLY ] [ [ IF NOT EXISTS ] <em class="replaceable"><code>name</code></em> ] ON [ ONLY ] <em class="replaceable"><code>table_name</code></em> [ USING <em class="replaceable"><code>method</code></em> ]4 ( { <em class="replaceable"><code>column_name</code></em> | ( <em class="replaceable"><code>expression</code></em> ) } [ COLLATE <em class="replaceable"><code>collation</code></em> ] [ <em class="replaceable"><code>opclass</code></em> [ ( <em class="replaceable"><code>opclass_parameter</code></em> = <em class="replaceable"><code>value</code></em> [, ... ] ) ] ] [ ASC | DESC ] [ NULLS { FIRST | LAST } ] [, ...] )5 [ INCLUDE ( <em class="replaceable"><code>column_name</code></em> [, ...] ) ]6 [ NULLS [ NOT ] DISTINCT ]7 [ WITH ( <em class="replaceable"><code>storage_parameter</code></em> [= <em class="replaceable"><code>value</code></em>] [, ... ] ) ]8 [ TABLESPACE <em class="replaceable"><code>tablespace_name</code></em> ]9 [ WHERE <em class="replaceable"><code>predicate</code></em> ]10</pre></div><div class="refsect1" id="id-1.9.3.69.5"><h2>Description</h2><p>11 <code class="command">CREATE INDEX</code> constructs an index on the specified column(s)12 of the specified relation, which can be a table or a materialized view.13 Indexes are primarily used to enhance database performance (though14 inappropriate use can result in slower performance).15 </p><p>16 The key field(s) for the index are specified as column names,17 or alternatively as expressions written in parentheses.18 Multiple fields can be specified if the index method supports19 multicolumn indexes.20 </p><p>21 An index field can be an expression computed from the values of22 one or more columns of the table row. This feature can be used23 to obtain fast access to data based on some transformation of24 the basic data. For example, an index computed on25 <code class="literal">upper(col)</code> would allow the clause26 <code class="literal">WHERE upper(col) = 'JIM'</code> to use an index.27 </p><p>28 <span class="productname">PostgreSQL</span> provides the index methods29 B-tree, hash, GiST, SP-GiST, GIN, and BRIN. Users can also define their own30 index methods, but that is fairly complicated.31 </p><p>32 When the <code class="literal">WHERE</code> clause is present, a33 <em class="firstterm">partial index</em> is created.34 A partial index is an index that contains entries for only a portion of35 a table, usually a portion that is more useful for indexing than the36 rest of the table. For example, if you have a table that contains both37 billed and unbilled orders where the unbilled orders take up a small38 fraction of the total table and yet that is an often used section, you39 can improve performance by creating an index on just that portion.40 Another possible application is to use <code class="literal">WHERE</code> with41 <code class="literal">UNIQUE</code> to enforce uniqueness over a subset of a42 table. See <a class="xref" href="indexes-partial.html" title="11.8. Partial Indexes">Section 11.8</a> for more discussion.43 </p><p>44 The expression used in the <code class="literal">WHERE</code> clause can refer45 only to columns of the underlying table, but it can use all columns,46 not just the ones being indexed. Presently, subqueries and47 aggregate expressions are also forbidden in <code class="literal">WHERE</code>.48 The same restrictions apply to index fields that are expressions.49 </p><p>50 All functions and operators used in an index definition must be51 <span class="quote">“<span class="quote">immutable</span>”</span>, that is, their results must depend only on52 their arguments and never on any outside influence (such as53 the contents of another table or the current time). This restriction54 ensures that the behavior of the index is well-defined. To use a55 user-defined function in an index expression or <code class="literal">WHERE</code>56 clause, remember to mark the function immutable when you create it.57 </p></div><div class="refsect1" id="id-1.9.3.69.6"><h2>Parameters</h2><div class="variablelist"><dl class="variablelist"><dt><span class="term"><code class="literal">UNIQUE</code></span></dt><dd><p>58 Causes the system to check for59 duplicate values in the table when the index is created (if data60 already exist) and each time data is added. Attempts to61 insert or update data which would result in duplicate entries62 will generate an error.63 </p><p>64 Additional restrictions apply when unique indexes are applied to65 partitioned tables; see <a class="xref" href="sql-createtable.html" title="CREATE TABLE"><span class="refentrytitle">CREATE TABLE</span></a>.66 </p></dd><dt><span class="term"><code class="literal">CONCURRENTLY</code></span></dt><dd><p>67 When this option is used, <span class="productname">PostgreSQL</span> will build the68 index without taking any locks that prevent concurrent inserts,69 updates, or deletes on the table; whereas a standard index build70 locks out writes (but not reads) on the table until it's done.71 There are several caveats to be aware of when using this option72 — see <a class="xref" href="sql-createindex.html#SQL-CREATEINDEX-CONCURRENTLY" title="Building Indexes Concurrently">Building Indexes Concurrently</a> below.73 </p><p>74 For temporary tables, <code class="command">CREATE INDEX</code> is always75 non-concurrent, as no other session can access them, and76 non-concurrent index creation is cheaper.77 </p></dd><dt><span class="term"><code class="literal">IF NOT EXISTS</code></span></dt><dd><p>78 Do not throw an error if a relation with the same name already exists.79 A notice is issued in this case. Note that there is no guarantee that80 the existing index is anything like the one that would have been created.81 Index name is required when <code class="literal">IF NOT EXISTS</code> is specified.82 </p></dd><dt><span class="term"><code class="literal">INCLUDE</code></span></dt><dd><p>83 The optional <code class="literal">INCLUDE</code> clause specifies a84 list of columns which will be included in the index85 as <em class="firstterm">non-key</em> columns. A non-key column cannot86 be used in an index scan search qualification, and it is disregarded87 for purposes of any uniqueness or exclusion constraint enforced by88 the index. However, an index-only scan can return the contents of89 non-key columns without having to visit the index's table, since90 they are available directly from the index entry. Thus, addition of91 non-key columns allows index-only scans to be used for queries that92 otherwise could not use them.93 </p><p>94 It's wise to be conservative about adding non-key columns to an95 index, especially wide columns. If an index tuple exceeds the96 maximum size allowed for the index type, data insertion will fail.97 In any case, non-key columns duplicate data from the index's table98 and bloat the size of the index, thus potentially slowing searches.99 Furthermore, B-tree deduplication is never used with indexes100 that have a non-key column.101 </p><p>102 Columns listed in the <code class="literal">INCLUDE</code> clause don't need103 appropriate operator classes; the clause can include104 columns whose data types don't have operator classes defined for105 a given access method.106 </p><p>107 Expressions are not supported as included columns since they cannot be108 used in index-only scans.109 </p><p>110 Currently, the B-tree, GiST and SP-GiST index access methods support111 this feature. In these indexes, the values of columns listed112 in the <code class="literal">INCLUDE</code> clause are included in leaf tuples113 which correspond to heap tuples, but are not included in upper-level114 index entries used for tree navigation.115 </p></dd><dt><span class="term"><em class="replaceable"><code>name</code></em></span></dt><dd><p>116 The name of the index to be created. No schema name can be included117 here; the index is always created in the same schema as its parent118 table. The name of the index must be distinct from the name of any119 other relation (table, sequence, index, view, materialized view, or120 foreign table) in that schema.121 If the name is omitted, <span class="productname">PostgreSQL</span> chooses a122 suitable name based on the parent table's name and the indexed column123 name(s).124 </p></dd><dt><span class="term"><code class="literal">ONLY</code></span></dt><dd><p>125 Indicates not to recurse creating indexes on partitions, if the126 table is partitioned. The default is to recurse.127 </p></dd><dt><span class="term"><em class="replaceable"><code>table_name</code></em></span></dt><dd><p>128 The name (possibly schema-qualified) of the table to be indexed.129 </p></dd><dt><span class="term"><em class="replaceable"><code>method</code></em></span></dt><dd><p>130 The name of the index method to be used. Choices are131 <code class="literal">btree</code>, <code class="literal">hash</code>,132 <code class="literal">gist</code>, <code class="literal">spgist</code>, <code class="literal">gin</code>,133 <code class="literal">brin</code>, or user-installed access methods like134 <a class="link" href="bloom.html" title="F.7. bloom — bloom filter index access method">bloom</a>.135 The default method is <code class="literal">btree</code>.136 </p></dd><dt><span class="term"><em class="replaceable"><code>column_name</code></em></span></dt><dd><p>137 The name of a column of the table.138 </p></dd><dt><span class="term"><em class="replaceable"><code>expression</code></em></span></dt><dd><p>139 An expression based on one or more columns of the table. The140 expression usually must be written with surrounding parentheses,141 as shown in the syntax. However, the parentheses can be omitted142 if the expression has the form of a function call.143 </p></dd><dt><span class="term"><em class="replaceable"><code>collation</code></em></span></dt><dd><p>144 The name of the collation to use for the index. By default,145 the index uses the collation declared for the column to be146 indexed or the result collation of the expression to be147 indexed. Indexes with non-default collations can be useful for148 queries that involve expressions using non-default collations.149 </p></dd><dt><span class="term"><em class="replaceable"><code>opclass</code></em></span></dt><dd><p>150 The name of an operator class. See below for details.151 </p></dd><dt><span class="term"><em class="replaceable"><code>opclass_parameter</code></em></span></dt><dd><p>152 The name of an operator class parameter. See below for details.153 </p></dd><dt><span class="term"><code class="literal">ASC</code></span></dt><dd><p>154 Specifies ascending sort order (which is the default).155 </p></dd><dt><span class="term"><code class="literal">DESC</code></span></dt><dd><p>156 Specifies descending sort order.157 </p></dd><dt><span class="term"><code class="literal">NULLS FIRST</code></span></dt><dd><p>158 Specifies that nulls sort before non-nulls. This is the default159 when <code class="literal">DESC</code> is specified.160 </p></dd><dt><span class="term"><code class="literal">NULLS LAST</code></span></dt><dd><p>161 Specifies that nulls sort after non-nulls. This is the default162 when <code class="literal">DESC</code> is not specified.163 </p></dd><dt><span class="term"><code class="literal">NULLS DISTINCT</code><br /></span><span class="term"><code class="literal">NULLS NOT DISTINCT</code></span></dt><dd><p>164 Specifies whether for a unique index, null values should be considered165 distinct (not equal). The default is that they are distinct, so that166 a unique index could contain multiple null values in a column.167 </p></dd><dt><span class="term"><em class="replaceable"><code>storage_parameter</code></em></span></dt><dd><p>168 The name of an index-method-specific storage parameter. See169 <a class="xref" href="sql-createindex.html#SQL-CREATEINDEX-STORAGE-PARAMETERS" title="Index Storage Parameters">Index Storage Parameters</a> below170 for details.171 </p></dd><dt><span class="term"><em class="replaceable"><code>tablespace_name</code></em></span></dt><dd><p>172 The tablespace in which to create the index. If not specified,173 <a class="xref" href="runtime-config-client.html#GUC-DEFAULT-TABLESPACE">default_tablespace</a> is consulted, or174 <a class="xref" href="runtime-config-client.html#GUC-TEMP-TABLESPACES">temp_tablespaces</a> for indexes on temporary175 tables.176 </p></dd><dt><span class="term"><em class="replaceable"><code>predicate</code></em></span></dt><dd><p>177 The constraint expression for a partial index.178 </p></dd></dl></div><div class="refsect2" id="SQL-CREATEINDEX-STORAGE-PARAMETERS"><h3>Index Storage Parameters</h3><p>179 The optional <code class="literal">WITH</code> clause specifies <em class="firstterm">storage180 parameters</em> for the index. Each index method has its own set of allowed181 storage parameters. The B-tree, hash, GiST and SP-GiST index methods all182 accept this parameter:183 </p><div class="variablelist"><dl class="variablelist"><dt id="INDEX-RELOPTION-FILLFACTOR"><span class="term"><code class="literal">fillfactor</code> (<code class="type">integer</code>)184 <a id="id-1.9.3.69.6.3.3.1.1.3" class="indexterm"></a>185 </span> <a href="#INDEX-RELOPTION-FILLFACTOR" class="id_link">#</a></dt><dd><p>186 The fillfactor for an index is a percentage that determines how full187 the index method will try to pack index pages. For B-trees, leaf pages188 are filled to this percentage during initial index builds, and also189 when extending the index at the right (adding new largest key values).190 If pages191 subsequently become completely full, they will be split, leading to192 fragmentation of the on-disk index structure. B-trees use a default193 fillfactor of 90, but any integer value from 10 to 100 can be selected.194 </p><p>195 B-tree indexes on tables where many inserts and/or updates are196 anticipated can benefit from lower fillfactor settings at197 <code class="command">CREATE INDEX</code> time (following bulk loading into the198 table). Values in the range of 50 - 90 can usefully <span class="quote">“<span class="quote">smooth199 out</span>”</span> the <span class="emphasis"><em>rate</em></span> of page splits during the200 early life of the B-tree index (lowering fillfactor like this may even201 lower the absolute number of page splits, though this effect is highly202 workload dependent). The B-tree bottom-up index deletion technique203 described in <a class="xref" href="btree-implementation.html#BTREE-DELETION" title="67.4.2. Bottom-up Index Deletion">Section 67.4.2</a> is dependent on having204 some <span class="quote">“<span class="quote">extra</span>”</span> space on pages to store <span class="quote">“<span class="quote">extra</span>”</span>205 tuple versions, and so can be affected by fillfactor (though the effect206 is usually not significant).207 </p><p>208 In other specific cases it might be useful to increase fillfactor to209 100 at <code class="command">CREATE INDEX</code> time as a way of maximizing210 space utilization. You should only consider this when you are211 completely sure that the table is static (i.e. that it will never be212 affected by either inserts or updates). A fillfactor setting of 100213 otherwise risks <span class="emphasis"><em>harming</em></span> performance: even a few214 updates or inserts will cause a sudden flood of page splits.215 </p><p>216 The other index methods use fillfactor in different but roughly217 analogous ways; the default fillfactor varies between methods.218 </p></dd></dl></div><p>219 B-tree indexes additionally accept this parameter:220 </p><div class="variablelist"><dl class="variablelist"><dt id="INDEX-RELOPTION-DEDUPLICATE-ITEMS"><span class="term"><code class="literal">deduplicate_items</code> (<code class="type">boolean</code>)221 <a id="id-1.9.3.69.6.3.5.1.1.3" class="indexterm"></a>222 </span> <a href="#INDEX-RELOPTION-DEDUPLICATE-ITEMS" class="id_link">#</a></dt><dd><p>223 Controls usage of the B-tree deduplication technique described224 in <a class="xref" href="btree-implementation.html#BTREE-DEDUPLICATION" title="67.4.3. Deduplication">Section 67.4.3</a>. Set to225 <code class="literal">ON</code> or <code class="literal">OFF</code> to enable or226 disable the optimization. (Alternative spellings of227 <code class="literal">ON</code> and <code class="literal">OFF</code> are allowed as228 described in <a class="xref" href="config-setting.html" title="20.1. Setting Parameters">Section 20.1</a>.) The default is229 <code class="literal">ON</code>.230 </p><div class="note"><h3 class="title">Note</h3><p>231 Turning <code class="literal">deduplicate_items</code> off via232 <code class="command">ALTER INDEX</code> prevents future insertions from233 triggering deduplication, but does not in itself make existing234 posting list tuples use the standard tuple representation.235 </p></div></dd></dl></div><p>236 GiST indexes additionally accept this parameter:237 </p><div class="variablelist"><dl class="variablelist"><dt id="INDEX-RELOPTION-BUFFERING"><span class="term"><code class="literal">buffering</code> (<code class="type">enum</code>)238 <a id="id-1.9.3.69.6.3.7.1.1.3" class="indexterm"></a>239 </span> <a href="#INDEX-RELOPTION-BUFFERING" class="id_link">#</a></dt><dd><p>240 Determines whether the buffered build technique described in241 <a class="xref" href="gist-implementation.html#GIST-BUFFERING-BUILD" title="68.4.1. GiST Index Build Methods">Section 68.4.1</a> is used to build the index. With242 <code class="literal">OFF</code> buffering is disabled, with <code class="literal">ON</code>243 it is enabled, and with <code class="literal">AUTO</code> it is initially disabled,244 but is turned on on-the-fly once the index size reaches245 <a class="xref" href="runtime-config-query.html#GUC-EFFECTIVE-CACHE-SIZE">effective_cache_size</a>. The default246 is <code class="literal">AUTO</code>.247 Note that if sorted build is possible, it will be used instead of248 buffered build unless <code class="literal">buffering=ON</code> is specified.249 </p></dd></dl></div><p>250 GIN indexes accept different parameters:251 </p><div class="variablelist"><dl class="variablelist"><dt id="INDEX-RELOPTION-FASTUPDATE"><span class="term"><code class="literal">fastupdate</code> (<code class="type">boolean</code>)252 <a id="id-1.9.3.69.6.3.9.1.1.3" class="indexterm"></a>253 </span> <a href="#INDEX-RELOPTION-FASTUPDATE" class="id_link">#</a></dt><dd><p>254 This setting controls usage of the fast update technique described in255 <a class="xref" href="gin-implementation.html#GIN-FAST-UPDATE" title="70.4.1. GIN Fast Update Technique">Section 70.4.1</a>. It is a Boolean parameter:256 <code class="literal">ON</code> enables fast update, <code class="literal">OFF</code> disables it.257 The default is <code class="literal">ON</code>.258 </p><div class="note"><h3 class="title">Note</h3><p>259 Turning <code class="literal">fastupdate</code> off via <code class="command">ALTER INDEX</code> prevents260 future insertions from going into the list of pending index entries,261 but does not in itself flush previous entries. You might want to262 <code class="command">VACUUM</code> the table or call <code class="function">gin_clean_pending_list</code>263 function afterward to ensure the pending list is emptied.264 </p></div></dd></dl></div><div class="variablelist"><dl class="variablelist"><dt id="INDEX-RELOPTION-GIN-PENDING-LIST-LIMIT"><span class="term"><code class="literal">gin_pending_list_limit</code> (<code class="type">integer</code>)265 <a id="id-1.9.3.69.6.3.10.1.1.3" class="indexterm"></a>266 </span> <a href="#INDEX-RELOPTION-GIN-PENDING-LIST-LIMIT" class="id_link">#</a></dt><dd><p>267 Custom <a class="xref" href="runtime-config-client.html#GUC-GIN-PENDING-LIST-LIMIT">gin_pending_list_limit</a> parameter.268 This value is specified in kilobytes.269 </p></dd></dl></div><p>270 <acronym class="acronym">BRIN</acronym> indexes accept different parameters:271 </p><div class="variablelist"><dl class="variablelist"><dt id="INDEX-RELOPTION-PAGES-PER-RANGE"><span class="term"><code class="literal">pages_per_range</code> (<code class="type">integer</code>)272 <a id="id-1.9.3.69.6.3.12.1.1.3" class="indexterm"></a>273 </span> <a href="#INDEX-RELOPTION-PAGES-PER-RANGE" class="id_link">#</a></dt><dd><p>274 Defines the number of table blocks that make up one block range for275 each entry of a <acronym class="acronym">BRIN</acronym> index (see <a class="xref" href="brin-intro.html" title="71.1. Introduction">Section 71.1</a>276 for more details). The default is <code class="literal">128</code>.277 </p></dd><dt id="INDEX-RELOPTION-AUTOSUMMARIZE"><span class="term"><code class="literal">autosummarize</code> (<code class="type">boolean</code>)278 <a id="id-1.9.3.69.6.3.12.2.1.3" class="indexterm"></a>279 </span> <a href="#INDEX-RELOPTION-AUTOSUMMARIZE" class="id_link">#</a></dt><dd><p>280 Defines whether a summarization run is queued for the previous page281 range whenever an insertion is detected on the next one.282 See <a class="xref" href="brin-intro.html#BRIN-OPERATION" title="71.1.1. Index Maintenance">Section 71.1.1</a> for more details.283 The default is <code class="literal">off</code>.284 </p></dd></dl></div></div><div class="refsect2" id="SQL-CREATEINDEX-CONCURRENTLY"><h3>Building Indexes Concurrently</h3><a id="id-1.9.3.69.6.4.2" class="indexterm"></a><p>285 Creating an index can interfere with regular operation of a database.286 Normally <span class="productname">PostgreSQL</span> locks the table to be indexed against287 writes and performs the entire index build with a single scan of the288 table. Other transactions can still read the table, but if they try to289 insert, update, or delete rows in the table they will block until the290 index build is finished. This could have a severe effect if the system is291 a live production database. Very large tables can take many hours to be292 indexed, and even for smaller tables, an index build can lock out writers293 for periods that are unacceptably long for a production system.294 </p><p>295 <span class="productname">PostgreSQL</span> supports building indexes without locking296 out writes. This method is invoked by specifying the297 <code class="literal">CONCURRENTLY</code> option of <code class="command">CREATE INDEX</code>.298 When this option is used,299 <span class="productname">PostgreSQL</span> must perform two scans of the table, and in300 addition it must wait for all existing transactions that could potentially301 modify or use the index to terminate. Thus302 this method requires more total work than a standard index build and takes303 significantly longer to complete. However, since it allows normal304 operations to continue while the index is built, this method is useful for305 adding new indexes in a production environment. Of course, the extra CPU306 and I/O load imposed by the index creation might slow other operations.307 </p><p>308 In a concurrent index build, the index is actually entered as an309 <span class="quote">“<span class="quote">invalid</span>”</span> index into310 the system catalogs in one transaction, then two table scans occur in311 two more transactions. Before each table scan, the index build must312 wait for existing transactions that have modified the table to terminate.313 After the second scan, the index build must wait for any transactions314 that have a snapshot (see <a class="xref" href="mvcc.html" title="Chapter 13. Concurrency Control">Chapter 13</a>) predating the second315 scan to terminate, including transactions used by any phase of concurrent316 index builds on other tables, if the indexes involved are partial or have317 columns that are not simple column references.318 Then finally the index can be marked <span class="quote">“<span class="quote">valid</span>”</span> and ready for use,319 and the <code class="command">CREATE INDEX</code> command terminates.320 Even then, however, the index may not be immediately usable for queries:321 in the worst case, it cannot be used as long as transactions exist that322 predate the start of the index build.323 </p><p>324 If a problem arises while scanning the table, such as a deadlock or a325 uniqueness violation in a unique index, the <code class="command">CREATE INDEX</code>326 command will fail but leave behind an <span class="quote">“<span class="quote">invalid</span>”</span> index. This index327 will be ignored for querying purposes because it might be incomplete;328 however it will still consume update overhead. The <span class="application">psql</span>329 <code class="command">\d</code> command will report such an index as <code class="literal">INVALID</code>:330 331</p><pre class="programlisting">332postgres=# \d tab333 Table "public.tab"334 Column | Type | Collation | Nullable | Default335--------+---------+-----------+----------+---------336 col | integer | | |337Indexes:338 "idx" btree (col) INVALID339</pre><p>340 341 The recommended recovery342 method in such cases is to drop the index and try again to perform343 <code class="command">CREATE INDEX CONCURRENTLY</code>. (Another possibility is344 to rebuild the index with <code class="command">REINDEX INDEX CONCURRENTLY</code>).345 </p><p>346 Another caveat when building a unique index concurrently is that the347 uniqueness constraint is already being enforced against other transactions348 when the second table scan begins. This means that constraint violations349 could be reported in other queries prior to the index becoming available350 for use, or even in cases where the index build eventually fails. Also,351 if a failure does occur in the second scan, the <span class="quote">“<span class="quote">invalid</span>”</span> index352 continues to enforce its uniqueness constraint afterwards.353 </p><p>354 Concurrent builds of expression indexes and partial indexes are supported.355 Errors occurring in the evaluation of these expressions could cause356 behavior similar to that described above for unique constraint violations.357 </p><p>358 Regular index builds permit other regular index builds on the359 same table to occur simultaneously, but only one concurrent index build360 can occur on a table at a time. In either case, schema modification of the361 table is not allowed while the index is being built. Another difference is362 that a regular <code class="command">CREATE INDEX</code> command can be performed363 within a transaction block, but <code class="command">CREATE INDEX CONCURRENTLY</code>364 cannot.365 </p><p>366 Concurrent builds for indexes on partitioned tables are currently not367 supported. However, you may concurrently build the index on each368 partition individually and then finally create the partitioned index369 non-concurrently in order to reduce the time where writes to the370 partitioned table will be locked out. In this case, building the371 partitioned index is a metadata only operation.372 </p></div></div><div class="refsect1" id="id-1.9.3.69.7"><h2>Notes</h2><p>373 See <a class="xref" href="indexes.html" title="Chapter 11. Indexes">Chapter 11</a> for information about when indexes can374 be used, when they are not used, and in which particular situations375 they can be useful.376 </p><p>377 Currently, only the B-tree, GiST, GIN, and BRIN index methods support378 multiple-key-column indexes. Whether there can be multiple key379 columns is independent of whether <code class="literal">INCLUDE</code> columns380 can be added to the index. Indexes can have up to 32 columns,381 including <code class="literal">INCLUDE</code> columns.382 (This limit can be altered when building383 <span class="productname">PostgreSQL</span>.) Only B-tree currently384 supports unique indexes.385 </p><p>386 An <em class="firstterm">operator class</em> with optional parameters387 can be specified for each column of an index.388 The operator class identifies the operators to be389 used by the index for that column. For example, a B-tree index on390 four-byte integers would use the <code class="literal">int4_ops</code> class;391 this operator class includes comparison functions for four-byte392 integers. In practice the default operator class for the column's data393 type is usually sufficient. The main point of having operator classes394 is that for some data types, there could be more than one meaningful395 ordering. For example, we might want to sort a complex-number data396 type either by absolute value or by real part. We could do this by397 defining two operator classes for the data type and then selecting398 the proper class when creating an index. More information about399 operator classes is in <a class="xref" href="indexes-opclass.html" title="11.10. Operator Classes and Operator Families">Section 11.10</a> and in <a class="xref" href="xindex.html" title="38.16. Interfacing Extensions to Indexes">Section 38.16</a>.400 </p><p>401 When <code class="literal">CREATE INDEX</code> is invoked on a partitioned402 table, the default behavior is to recurse to all partitions to ensure403 they all have matching indexes.404 Each partition is first checked to determine whether an equivalent405 index already exists, and if so, that index will become attached as a406 partition index to the index being created, which will become its407 parent index.408 If no matching index exists, a new index will be created and409 automatically attached; the name of the new index in each partition410 will be determined as if no index name had been specified in the411 command.412 If the <code class="literal">ONLY</code> option is specified, no recursion413 is done, and the index is marked invalid.414 (<code class="command">ALTER INDEX ... ATTACH PARTITION</code> marks the index415 valid, once all partitions acquire matching indexes.) Note, however,416 that any partition that is created in the future using417 <code class="command">CREATE TABLE ... PARTITION OF</code> will automatically418 have a matching index, regardless of whether <code class="literal">ONLY</code> is419 specified.420 </p><p>421 For index methods that support ordered scans (currently, only B-tree),422 the optional clauses <code class="literal">ASC</code>, <code class="literal">DESC</code>, <code class="literal">NULLS423 FIRST</code>, and/or <code class="literal">NULLS LAST</code> can be specified to modify424 the sort ordering of the index. Since an ordered index can be425 scanned either forward or backward, it is not normally useful to create a426 single-column <code class="literal">DESC</code> index — that sort ordering is already427 available with a regular index. The value of these options is that428 multicolumn indexes can be created that match the sort ordering requested429 by a mixed-ordering query, such as <code class="literal">SELECT ... ORDER BY x ASC, y430 DESC</code>. The <code class="literal">NULLS</code> options are useful if you need to support431 <span class="quote">“<span class="quote">nulls sort low</span>”</span> behavior, rather than the default <span class="quote">“<span class="quote">nulls432 sort high</span>”</span>, in queries that depend on indexes to avoid sorting steps.433 </p><p>434 The system regularly collects statistics on all of a table's435 columns. Newly-created non-expression indexes can immediately436 use these statistics to determine an index's usefulness.437 For new expression indexes, it is necessary to run <a class="link" href="sql-analyze.html" title="ANALYZE"><code class="command">ANALYZE</code></a> or wait for438 the <a class="link" href="routine-vacuuming.html#AUTOVACUUM" title="25.1.6. The Autovacuum Daemon">autovacuum daemon</a> to analyze439 the table to generate statistics for these indexes.440 </p><p>441 For most index methods, the speed of creating an index is442 dependent on the setting of <a class="xref" href="runtime-config-resource.html#GUC-MAINTENANCE-WORK-MEM">maintenance_work_mem</a>.443 Larger values will reduce the time needed for index creation, so long444 as you don't make it larger than the amount of memory really available,445 which would drive the machine into swapping.446 </p><p>447 <span class="productname">PostgreSQL</span> can build indexes while448 leveraging multiple CPUs in order to process the table rows faster.449 This feature is known as <em class="firstterm">parallel index450 build</em>. For index methods that support building indexes451 in parallel (currently, only B-tree),452 <code class="varname">maintenance_work_mem</code> specifies the maximum453 amount of memory that can be used by each index build operation as454 a whole, regardless of how many worker processes were started.455 Generally, a cost model automatically determines how many worker456 processes should be requested, if any.457 </p><p>458 Parallel index builds may benefit from increasing459 <code class="varname">maintenance_work_mem</code> where an equivalent serial460 index build will see little or no benefit. Note that461 <code class="varname">maintenance_work_mem</code> may influence the number of462 worker processes requested, since parallel workers must have at463 least a <code class="literal">32MB</code> share of the total464 <code class="varname">maintenance_work_mem</code> budget. There must also be465 a remaining <code class="literal">32MB</code> share for the leader process.466 Increasing <a class="xref" href="runtime-config-resource.html#GUC-MAX-PARALLEL-MAINTENANCE-WORKERS">max_parallel_maintenance_workers</a>467 may allow more workers to be used, which will reduce the time468 needed for index creation, so long as the index build is not469 already I/O bound. Of course, there should also be sufficient470 CPU capacity that would otherwise lie idle.471 </p><p>472 Setting a value for <code class="literal">parallel_workers</code> via <a class="link" href="sql-altertable.html" title="ALTER TABLE"><code class="command">ALTER TABLE</code></a> directly controls how many parallel473 worker processes will be requested by a <code class="command">CREATE474 INDEX</code> against the table. This bypasses the cost model475 completely, and prevents <code class="varname">maintenance_work_mem</code>476 from affecting how many parallel workers are requested. Setting477 <code class="literal">parallel_workers</code> to 0 via <code class="command">ALTER478 TABLE</code> will disable parallel index builds on the table in479 all cases.480 </p><div class="tip"><h3 class="title">Tip</h3><p>481 You might want to reset <code class="literal">parallel_workers</code> after482 setting it as part of tuning an index build. This avoids483 inadvertent changes to query plans, since484 <code class="literal">parallel_workers</code> affects485 <span class="emphasis"><em>all</em></span> parallel table scans.486 </p></div><p>487 While <code class="command">CREATE INDEX</code> with the488 <code class="literal">CONCURRENTLY</code> option supports parallel builds489 without special restrictions, only the first table scan is actually490 performed in parallel.491 </p><p>492 Use <a class="link" href="sql-dropindex.html" title="DROP INDEX"><code class="command">DROP INDEX</code></a>493 to remove an index.494 </p><p>495 Like any long-running transaction, <code class="command">CREATE INDEX</code> on a496 table can affect which tuples can be removed by concurrent497 <code class="command">VACUUM</code> on any other table.498 </p><p>499 Prior releases of <span class="productname">PostgreSQL</span> also had an500 R-tree index method. This method has been removed because501 it had no significant advantages over the GiST method.502 If <code class="literal">USING rtree</code> is specified, <code class="command">CREATE INDEX</code>503 will interpret it as <code class="literal">USING gist</code>, to simplify conversion504 of old databases to GiST.505 </p><p>506 Each backend running <code class="command">CREATE INDEX</code> will report its507 progress in the <code class="structname">pg_stat_progress_create_index</code>508 view. See <a class="xref" href="progress-reporting.html#CREATE-INDEX-PROGRESS-REPORTING" title="28.4.4. CREATE INDEX Progress Reporting">Section 28.4.4</a> for details.509 </p></div><div class="refsect1" id="id-1.9.3.69.8"><h2>Examples</h2><p>510 To create a unique B-tree index on the column <code class="literal">title</code> in511 the table <code class="literal">films</code>:512</p><pre class="programlisting">513CREATE UNIQUE INDEX title_idx ON films (title);514</pre><p>515 </p><p>516 To create a unique B-tree index on the column <code class="literal">title</code>517 with included columns <code class="literal">director</code>518 and <code class="literal">rating</code> in the table <code class="literal">films</code>:519</p><pre class="programlisting">520CREATE UNIQUE INDEX title_idx ON films (title) INCLUDE (director, rating);521</pre><p>522 </p><p>523 To create a B-Tree index with deduplication disabled:524</p><pre class="programlisting">525CREATE INDEX title_idx ON films (title) WITH (deduplicate_items = off);526</pre><p>527 </p><p>528 To create an index on the expression <code class="literal">lower(title)</code>,529 allowing efficient case-insensitive searches:530</p><pre class="programlisting">531CREATE INDEX ON films ((lower(title)));532</pre><p>533 (In this example we have chosen to omit the index name, so the system534 will choose a name, typically <code class="literal">films_lower_idx</code>.)535 </p><p>536 To create an index with non-default collation:537</p><pre class="programlisting">538CREATE INDEX title_idx_german ON films (title COLLATE "de_DE");539</pre><p>540 </p><p>541 To create an index with non-default sort ordering of nulls:542</p><pre class="programlisting">543CREATE INDEX title_idx_nulls_low ON films (title NULLS FIRST);544</pre><p>545 </p><p>546 To create an index with non-default fill factor:547</p><pre class="programlisting">548CREATE UNIQUE INDEX title_idx ON films (title) WITH (fillfactor = 70);549</pre><p>550 </p><p>551 To create a <acronym class="acronym">GIN</acronym> index with fast updates disabled:552</p><pre class="programlisting">553CREATE INDEX gin_idx ON documents_table USING GIN (locations) WITH (fastupdate = off);554</pre><p>555 </p><p>556 To create an index on the column <code class="literal">code</code> in the table557 <code class="literal">films</code> and have the index reside in the tablespace558 <code class="literal">indexspace</code>:559</p><pre class="programlisting">560CREATE INDEX code_idx ON films (code) TABLESPACE indexspace;561</pre><p>562 </p><p>563 To create a GiST index on a point attribute so that we564 can efficiently use box operators on the result of the565 conversion function:566</p><pre class="programlisting">567CREATE INDEX pointloc568 ON points USING gist (box(location,location));569SELECT * FROM points570 WHERE box(location,location) && '(0,0),(1,1)'::box;571</pre><p>572 </p><p>573 To create an index without locking out writes to the table:574</p><pre class="programlisting">575CREATE INDEX CONCURRENTLY sales_quantity_index ON sales_table (quantity);576</pre></div><div class="refsect1" id="id-1.9.3.69.9"><h2>Compatibility</h2><p>577 <code class="command">CREATE INDEX</code> is a578 <span class="productname">PostgreSQL</span> language extension. There579 are no provisions for indexes in the SQL standard.580 </p></div><div class="refsect1" id="id-1.9.3.69.10"><h2>See Also</h2><span class="simplelist"><a class="xref" href="sql-alterindex.html" title="ALTER INDEX"><span class="refentrytitle">ALTER INDEX</span></a>, <a class="xref" href="sql-dropindex.html" title="DROP INDEX"><span class="refentrytitle">DROP INDEX</span></a>, <a class="xref" href="sql-reindex.html" title="REINDEX"><span class="refentrytitle">REINDEX</span></a>, <a class="xref" href="progress-reporting.html#CREATE-INDEX-PROGRESS-REPORTING" title="28.4.4. CREATE INDEX Progress Reporting">Section 28.4.4</a></span></div></div><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="sql-creategroup.html" title="CREATE GROUP">Prev</a> </td><td width="20%" align="center"><a accesskey="u" href="sql-commands.html" title="SQL Commands">Up</a></td><td width="40%" align="right"> <a accesskey="n" href="sql-createlanguage.html" title="CREATE LANGUAGE">Next</a></td></tr><tr><td width="40%" align="left" valign="top">CREATE GROUP </td><td width="20%" align="center"><a accesskey="h" href="index.html" title="PostgreSQL 16.3 Documentation">Home</a></td><td width="40%" align="right" valign="top"> CREATE LANGUAGE</td></tr></table></div></body></html>