CREATE INDEX statement creates an index for a table. Indexes improve your database’s performance by helping SQL locate data without having to look through every row of a table.
Indexes are automatically created for a table’s PRIMARY KEY and UNIQUE columns.
Required privileges
You must have theCREATE privilege on the table.
Syntax
Parameters
Apply the
UNIQUE constraint to the indexed columns.This causes the system to check for existing duplicate values on index creation. It also applies the UNIQUE constraint at the table level, so the system checks for duplicate values when inserting or updating data.Create a GIN index on schemaless data in a
JSONB column.You can also use the PostgreSQL-compatible syntax USING GIN.Create a vector index on a
VECTOR column.Create a new index only if an index of the same name does not already exist. If one does exist, do not return an error.
The name of the index to create, which must be unique to its table.If you do not specify a name, CockroachDB uses the format
<table>_<columns>_key/idx. key indicates the index applies the UNIQUE constraint; idx indicates it does not.The name of the table you want to create the index on.
The name of the column you want to index.
Sort the column in ascending (
ASC) or descending (DESC) order in the index. How columns are sorted affects query results, particularly when using LIMIT.Default: ASCStore (but do not sort) each column whose name you include.Note: Columns that are part of a table’s
PRIMARY KEY cannot be specified as STORING columns in secondary indexes on the table.COVERING and INCLUDE are aliases for STORING and work identically.An optional
WHERE clause that defines the predicate boolean expression of a partial index.Examples
Create standard indexes
Single-column indexes
Single-column indexes sort the values of a single column:Multiple-column indexes
Multiple-column indexes sort columns in the order you list them:Unique indexes
Unique indexes do not allow duplicate values among their columns:UNIQUE constraint at the table level.
Create GIN indexes
You can create GIN indexes on schemaless data in aJSONB column:
Create trigram indexes
You can create trigram indexes onSTRING columns:
Create spatial indexes
You can create spatial indexes onGEOMETRY and GEOGRAPHY columns:
Store columns
Storing a column improves the performance of queries that retrieve (but do not filter) its values:Change column sort order
To sort columns in descending order, you must explicitly set the option:Query specific indexes
Normally, CockroachDB selects the index that it calculates will scan the fewest rows. However, you can override that selection:See also
- SHOW INDEX
- DROP INDEX
- ALTER INDEX
- SHOW JOBS