create_index.7
来自「PostgreSQL 8.2中增加了很多企业用户所需要的功能和性能上的提高,其开」· 7 代码 · 共 277 行
7
277 行
.\\" auto-generated by docbook2man-spec $Revision: 1.1.1.1 $.TH "CREATE INDEX" "" "2008-01-03" "SQL - Language Statements" "SQL Commands".SH NAMECREATE INDEX \- define a new index.SH SYNOPSIS.sp.nfCREATE [ UNIQUE ] INDEX [ CONCURRENTLY ] \fIname\fR ON \fItable\fR [ USING \fImethod\fR ] ( { \fIcolumn\fR | ( \fIexpression\fR ) } [ \fIopclass\fR ] [, ...] ) [ WITH ( \fIstorage_parameter\fR = \fIvalue\fR [, ... ] ) ] [ TABLESPACE \fItablespace\fR ] [ WHERE \fIpredicate\fR ].sp.fi.SH "DESCRIPTION".PP\fBCREATE INDEX\fR constructs an index \fIindex_name\fR on the specified table.Indexes are primarily used to enhance database performance (thoughinappropriate use can result in slower performance)..PPThe key field(s) for the index are specified as column names,or alternatively as expressions written in parentheses.Multiple fields can be specified if the index method supportsmulticolumn indexes..PPAn index field can be an expression computed from the values ofone or more columns of the table row. This feature can be usedto obtain fast access to data based on some transformation ofthe basic data. For example, an index computed onupper(col) would allow the clauseWHERE upper(col) = 'JIM' to use an index..PPPostgreSQL provides the index methodsB-tree, hash, GiST, and GIN. Users can also define their own indexmethods, but that is fairly complicated..PPWhen the WHERE clause is present, a\fIpartial index\fR is created.A partial index is an index that contains entries for only a portion ofa table, usually a portion that is more useful for indexing than therest of the table. For example, if you have a table that contains bothbilled and unbilled orders where the unbilled orders take up a smallfraction of the total table and yet that is an often used section, youcan improve performance by creating an index on just that portion.Another possible application is to use WHERE withUNIQUE to enforce uniqueness over a subset of atable. See in the documentation for more discussion..PPThe expression used in the WHERE clause may referonly to columns of the underlying table, but it can use all columns,not just the ones being indexed. Presently, subqueries andaggregate expressions are also forbidden in WHERE.The same restrictions apply to index fields that are expressions..PPAll functions and operators used in an index definition must be``immutable'', that is, their results must depend only ontheir arguments and never on any outside influence (such asthe contents of another table or the current time). This restrictionensures that the behavior of the index is well-defined. To use auser-defined function in an index expression or WHEREclause, remember to mark the function immutable when you create it..SH "PARAMETERS".TP\fBUNIQUE\fRCauses the system to check forduplicate values in the table when the index is created (if dataalready exist) and each time data is added. Attempts toinsert or update data which would result in duplicate entrieswill generate an error..TP\fBCONCURRENTLY\fRWhen this option is used, PostgreSQL will build theindex without taking any locks that prevent concurrent inserts,updates, or deletes on the table; whereas a standard index buildlocks out writes (but not reads) on the table until it's done.There are several caveats to be aware of when using this option\(em see Building Indexes Concurrently [\fBcreate_index\fR(7)]..TP\fB\fIname\fB\fRThe name of the index to be created. No schema name can be includedhere; the index is always created in the same schema as its parenttable..TP\fB\fItable\fB\fRThe name (possibly schema-qualified) of the table to be indexed..TP\fB\fImethod\fB\fRThe name of the index method to be used. Choices arebtree, hash,gist, and gin. Thedefault method is btree..TP\fB\fIcolumn\fB\fRThe name of a column of the table..TP\fB\fIexpression\fB\fRAn expression based on one or more columns of the table. Theexpression usually must be written with surrounding parentheses,as shown in the syntax. However, the parentheses may be omittedif the expression has the form of a function call..TP\fB\fIopclass\fB\fRThe name of an operator class. See below for details..TP\fB\fIstorage_parameter\fB\fRThe name of an index-method-specific storage parameter. Seebelow for details..TP\fB\fItablespace\fB\fRThe tablespace in which to create the index. If not specified,default_tablespace is used, or the database'sdefault tablespace if default_tablespace is an emptystring..TP\fB\fIpredicate\fB\fRThe constraint expression for a partial index..SS "INDEX STORAGE PARAMETERS".PPThe WITH clause can specify \fIstorage parameters\fRfor indexes. Each index method can have its own set of allowed storageparameters. The built-in index methods all accept a single parameter:.TP\fBFILLFACTOR\fRThe fillfactor for an index is a percentage that determines how fullthe index method will try to pack index pages. For B-trees, leaf pagesare filled to this percentage during initial index build, and alsowhen extending the index at the right (largest key values). If pagessubsequently become completely full, they will be split, leading togradual degradation in the index's efficiency. B-trees use a defaultfillfactor of 90, but any value from 10 to 100 can be selected.If the table is static then fillfactor 100 is best to minimize theindex's physical size, but for heavily updated tables a smallerfillfactor is better to minimize the need for page splits. Theother index methods use fillfactor in different but roughly analogousways; the default fillfactor varies between methods..SS "BUILDING INDEXES CONCURRENTLY".PPCreating an index can interfere with regular operation of a database.Normally PostgreSQL locks the table to be indexed againstwrites and performs the entire index build with a single scan of thetable. Other transactions can still read the table, but if they try toinsert, update, or delete rows in the table they will block until theindex build is finished. This could have a severe effect if the system isa live production database. Large tables can take many hours to beindexed, and even for smaller tables, an index build can lock out writersfor periods that are unacceptably long for a production system..PPPostgreSQL supports building indexes without lockingout writes. This method is invoked by specifying theCONCURRENTLY option of \fBCREATE INDEX\fR.When this option is used,PostgreSQL must perform two scans of the table, and inaddition it must wait for all existing transactions to terminate. Thusthis method requires more total work than a standard index build and takessignificantly longer to complete. However, since it allows normaloperations to continue while the index is built, this method is useful foradding new indexes in a production environment. Of course, the extra CPUand I/O load imposed by the index creation may slow other operations..PPIf a problem arises during the second scan of the table, such as auniqueness violation in a unique index, the \fBCREATE INDEX\fRcommand will fail but leave behind an ``invalid'' index. This indexwill be ignored for querying purposes because it may be incomplete;however it will still consume update overhead. The recommended recoverymethod in such cases is to drop the index and try again to perform\fBCREATE INDEX CONCURRENTLY\fR. (Another possibility is to rebuildthe index with \fBREINDEX\fR. However, since \fBREINDEX\fRdoes not support concurrent builds, this option is unlikely to seemattractive.).PPAnother caveat when building a unique index concurrently is that theuniqueness constraint is already being enforced against other transactionswhen the second table scan begins. This means that constraint violationscould be reported in other queries prior to the index becoming availablefor use, or even in cases where the index build eventually fails. Also,if a failure does occur in the second scan, the ``invalid'' indexcontinues to enforce its uniqueness constraint afterwards..PPConcurrent builds of expression indexes and partial indexes are supported.Errors occurring in the evaluation of these expressions could causebehavior similar to that described above for unique constraint violations..PPRegular index builds permit other regular index builds on thesame table to occur in parallel, but only one concurrent index buildcan occur on a table at a time. In both cases, no other types of schemamodification on the table are allowed meanwhile. Another differenceis that a regular \fBCREATE INDEX\fR command can be performed withina transaction block, but \fBCREATE INDEX CONCURRENTLY\fR cannot..SH "NOTES".PPSee in the documentation for information about when indexes canbe used, when they are not used, and in which particular situationsthey can be useful..PPCurrently, only the B-tree and GiST index methods supportmulticolumn indexes. Up to 32 fields may be specified by default.(This limit can be altered when buildingPostgreSQL.) Only B-tree currentlysupports unique indexes..PPAn \fIoperator class\fR can be specified for eachcolumn of an index. The operator class identifies the operators to beused by the index for that column. For example, a B-tree index onfour-byte integers would use the int4_ops class;this operator class includes comparison functions for four-byteintegers. In practice the default operator class for the column's datatype is usually sufficient. The main point of having operator classesis that for some data types, there could be more than one meaningfulordering. For example, we might want to sort a complex-number datatype either by absolute value or by real part. We could do this bydefining two operator classes for the data type and then selectingthe proper class when making an index. More information aboutoperator classes is in in the documentation and in in the documentation..PPUse DROP INDEX [\fBdrop_index\fR(7)]to remove an index..PPIndexes are not used for IS NULL clauses by default.The best way to use indexes in such cases is to create a partial indexusing an IS NULL predicate..PPPrior releases of PostgreSQL also had anR-tree index method. This method has been removed becauseit had no significant advantages over the GiST method.If USING rtree is specified, \fBCREATE INDEX\fRwill interpret it as USING gist, to simplify conversionof old databases to GiST..SH "EXAMPLES".PPTo create a B-tree index on the column title inthe table films:.sp.nfCREATE UNIQUE INDEX title_idx ON films (title);.sp.fi.PPTo create an index on the expression lower(title),allowing efficient case-insensitive searches:.sp.nfCREATE INDEX lower_title_idx ON films ((lower(title)));.sp.fi.PPTo create an index with non-default fill factor:.sp.nfCREATE UNIQUE INDEX title_idx ON films (title) WITH (fillfactor = 70);.sp.fi.PPTo create an index on the column code in the tablefilms and have the index reside in the tablespaceindexspace:.sp.nfCREATE INDEX code_idx ON films(code) TABLESPACE indexspace;.sp.fi.PPTo create an index without locking out writes to the table:.sp.nfCREATE INDEX CONCURRENTLY sales_quantity_index ON sales_table (quantity);.sp.fi.SH "COMPATIBILITY".PP\fBCREATE INDEX\fR is aPostgreSQL language extension. Thereare no provisions for indexes in the SQL standard..SH "SEE ALSO"ALTER INDEX [\fBalter_index\fR(7)], DROP INDEX [\fBdrop_index\fR(l)]
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?