Skip to main content
An expression index is an index created by applying an to a column. For example, to facilitate fast, case insensitive lookups of user names you could create an index by applying the function lower to the name column: CREATE INDEX users_name_idx ON users (lower(name)). The value of the expression is stored only in the expression index, not in the primary family index. Both and support expressions. You can use expressions in and . You can reference multiple columns in an expression index.

Create an expression index

To create an expression index, use the syntax:

View index expression

To view the expression used to generate the index, run SHOW CREATE TABLE:

Examples

Create various expression indexes

Suppose you have a table with the following columns:
The following examples illustrate how to create various types of expression indexes. A partial, multi-column index, where one column is defined with an expression:
A unique, partial, multi-column index, where one column is defined with an expression:
A GIN, partial, multi-column index, where one column is defined with an expression:

Use an expression to index a field in a JSONB column

You can use an expression in an index definition to index a field in a JSON column. You can also use an expression to create a on a subset of the JSON column. Normally an index is used only if the cost of using the index is less than the cost of a full table scan. To disable that optimization, turn off statistics collection:
Create a table of three users with a JSON object in the user_profile column:
When you perform a query that filters on the user_profile->'birthdate' column:
You can see that a full scan is performed:
To limit the number of rows scanned, create an expression index on the birthdate field:
When you filter on the expression parse_timestamp(user_profile->'birthdate'), only the row matching the filter is scanned:
As shown in this example, for an expression index to be used to service a query, the query must constrain the same exact expression in its filter.

Known limitations

Expression indexes have the following limitations:
  • The expression cannot reference columns outside the index’s table.
  • Functional expression output must be determined by the input arguments. For example, you can’t use the now() to create an index because its output depends on more than just the function arguments.
  • CockroachDB does not allow expression indexes to reference .
  • CockroachDB does not support expressions as ON CONFLICT targets. This means that unique expression indexes cannot be selected as arbiters for statements. For example:

See also