CREATE INDEX

Synopsis

This command creates an index on the specified column(s) of the specified table. Indexes are primarily used to improve query performance.

Syntax

  1. create_index ::= CREATE [ UNIQUE ] INDEX [ [ IF NOT EXISTS ] name ]
  2. ON [ ONLY ] table_name ( index_elem [ , ... ] )
  3. [ INCLUDE ( column_name [ , ... ] ) ]
  4. [ WHERE predicate ]
  5. index_elem ::= { column_name | ( expression ) }
  6. [ operator_class_name ] [ HASH | ASC | DESC ]
  7. [ NULLS { FIRST | LAST } ]

create_index

CREATE INDEX - 图1

index_elem

CREATE INDEX - 图2

Semantics

CONCURRENTLY, USING method, COLLATE, and TABLESPACE options are not yet supported.

UNIQUE

Enforce that duplicate values in a table are not allowed.

INCLUDE clause

Specify a list of columns which will be included in the index as non-key columns.

name

Specify the name of the index to be created.

table_name

Specify the name of the table to be indexed.

index_elem

column_name

Specify the name of a column of the table.

expression

Specify one or more columns of the table and must be surrounded by parentheses.

  • HASH - Use hash of the column. This is the default option for the first column and is used to hash partition the index table.
  • ASC — Sort in ascending order. This is the default option for second and subsequent columns of the index.
  • DESC — Sort in descending order.
  • NULLS FIRST - Specifies that nulls sort before non-nulls. This is the default when DESC is specified.
  • NULLS LAST - Specifies that nulls sort after non-nulls. This is the default when DESC is not specified.

Examples

Unique index with HASH column ordering

Create a unique index with hash ordered columns.

  1. yugabyte=# CREATE TABLE products(id int PRIMARY KEY,
  2. name text,
  3. code text);
  4. yugabyte=# CREATE UNIQUE INDEX ON products(code);
  5. yugabyte=# \d products
  6. Table "public.products"
  7. Column | Type | Collation | Nullable | Default
  8. --------+---------+-----------+----------+---------
  9. id | integer | | not null |
  10. name | text | | |
  11. code | text | | |
  12. Indexes:
  13. "products_pkey" PRIMARY KEY, lsm (id HASH)
  14. "products_code_idx" UNIQUE, lsm (code HASH)

ASC ordered index

Create an index with ascending ordered key.

  1. yugabyte=# CREATE INDEX products_name ON products(name ASC);
  2. yugabyte=# \d products_name
  3. Index "public.products_name"
  4. Column | Type | Key? | Definition
  5. --------+------+------+------------
  6. name | text | yes | name
  7. lsm, for table "public.products

INCLUDE columns

Create an index with ascending ordered key and include other columns as non-key columns

  1. yugabyte=# CREATE INDEX products_name_code ON products(name) INCLUDE (code);
  2. yugabyte=# \d products_name_code;
  3. Index "public.products_name_code"
  4. Column | Type | Key? | Definition
  5. --------+------+------+------------
  6. name | text | yes | name
  7. code | text | no | code
  8. lsm, for table "public.products"