---
title: "CREATE, ALTER and DROP INDEX"
description: "Create and manage CoraDB indexes: unique, descending, filtered and function-based indexes, online builds, ALTER INDEX and DROP INDEX."
url: "https://www.coradb.ai/manual/sql/schema/index_stmt.html"
markdown_url: "https://www.coradb.ai/manual/markdown/sql/schema/index_stmt.md"
product: "CoraDB"
version: "1.0"
keywords: "create index, create unique index, drop index, alter index, rebuild index, invisible index, online index, with online parallel, filtered index, function-based index, descending index, index comment, coradb index"
---

# CREATE, ALTER and DROP INDEX

An index lets CoraDB find rows by the values of one or more columns without reading the whole table. CoraDB indexes are B+trees. Primary keys, unique constraints and foreign keys create their indexes automatically; this page covers the indexes you create yourself. How the optimizer uses indexes, and how to steer it, is explained in [Query optimization](https://www.coradb.ai/manual/sql/tuning.html).

> **Try it yourself:**
> The examples run on the [e-commerce sample database](https://www.coradb.ai/manual/sample-database.html). Start corasql with `corasql --no-auto-commit -u dba e-commerce` and finish with `ROLLBACK;` to remove the indexes again.


## CREATE INDEX

```text
CREATE [UNIQUE] INDEX index_name ON table_name <index_definition>
    [WITH ONLINE [PARALLEL thread_count] | INVISIBLE | VISIBLE]
    [COMMENT 'comment']

<index_definition> ::=
      (column_name [ASC | DESC] [, column_name [ASC | DESC] ...]) [WHERE <filter_predicate>]
    | (function_name (argument_list))
```

- **UNIQUE**: no two rows can have the same key. `NULL` values do not count as duplicates.
- *index_name*: required, and unique within the table; see [Identifiers](https://www.coradb.ai/manual/sql/identifier.html).
- *column_name*: one or more columns. In a composite index, the order of the columns matters: the index can be searched by its first column, its first two columns, and so on.
- **ASC** | **DESC**: the order of the column in the index (default `ASC`).
- **WHERE** *filter_predicate*: a [filtered index](https://www.coradb.ai/manual/sql/tuning_special_index.html#filtered-index) contains only the rows that satisfy the predicate. Several conditions must be combined with `AND`.
- *function_name*(*argument_list*): a [function-based index](https://www.coradb.ai/manual/sql/tuning_special_index.html#function-based-index) stores the result of an expression, so queries that filter on the same expression can use it.
- **WITH ONLINE**: build the index while other transactions keep changing the table (see [Online index creation](https://www.coradb.ai/manual/sql/schema/index_stmt.html#online-index-creation)).
- **INVISIBLE**: create the index without letting the optimizer use it yet. `VISIBLE` is the default.
- **COMMENT**: a description of the index.

A descending index on product prices, and a composite index on a customer's orders, newest first:

```sql
CREATE INDEX idx_product_price ON product (unit_price DESC);

CREATE INDEX idx_orders_customer_date ON orders (customer_id, order_date DESC)
    COMMENT 'orders of a customer, newest first';
```

A filtered index that contains only unshipped orders, and a function-based index for case-insensitive searches on company names:

```sql
CREATE INDEX idx_orders_unshipped ON orders (customer_id, order_date) WHERE shipped_date IS NULL;

CREATE INDEX idx_customer_lower_name ON customer (LOWER(company_name));
```

A unique index rejects duplicates, like a `UNIQUE` constraint:

```sql
CREATE UNIQUE INDEX uq_countries_name ON countries (name);
INSERT INTO countries VALUES ('XXX', 'France');
```

```text
ERROR: Operation would have caused one or more unique constraint violations. INDEX uq_countries_name ... key: 'France'
```

Two indexes on the same columns with the same definition are not allowed: CoraDB reports `Index "..." already defined for class "..."`.

Index comments and visibility are listed by [SHOW INDEX](https://www.coradb.ai/manual/sql/query/show.html#show-index) and in the `db_index` catalog view:

```sql
SELECT index_name, is_unique, comment FROM db_index WHERE class_name = 'orders' ORDER BY index_name;
```

| index_name | is_unique | comment |
|---|---|---|
| fk_orders_customer_id | NO | NULL |
| idx_orders_customer_date | NO | Orders of a customer, newest first |
| idx_orders_order_date | NO | NULL |
| idx_orders_shipped_date | NO | NULL |
| idx_orders_unshipped | NO | NULL |
| pk_orders_id | YES | NULL |

> **Warning:**
> Do not change the session or server time zone, or the leap-second setting (see [Timezone parameter](https://www.coradb.ai/manual/admin/config_sql.html#timezone-parameter)), in a database that has indexes or function-based indexes on `TIMESTAMP`, `TIMESTAMP WITH LOCAL TIME ZONE` or `DATETIME WITH LOCAL TIME ZONE` columns: the stored keys would no longer match.


### Online index creation

A normal `CREATE INDEX` locks the table against changes until the index is built. `WITH ONLINE` keeps the table writable:

```sql
CREATE INDEX idx_order_items_discount ON order_items (discount_pct) WITH ONLINE PARALLEL 4;
```

The build has three stages:

1. The index is added to the schema with the status *online building*, under an exclusive schema lock that is then lowered so that other transactions can write to the table.
2. The table is scanned in batches; the batches are sorted and loaded into the index. Changes committed by other transactions in the meantime are applied to the index as well. `PARALLEL` *n* uses *n* threads to sort and load the batches (the table scan itself uses one thread).
3. The lock is raised again and the index status becomes normal.

While the build runs, other sessions see the index in [SHOW INDEX](https://www.coradb.ai/manual/sql/query/show.html#show-index) with `Visible = NO` and in `;schema` with the note `IN PROGRESS`. For a `UNIQUE` index, other transactions may commit rows that violate uniqueness during the build; the violation is detected at the end and the index creation fails with a unique constraint error. In standalone mode (`corasql -S`), `WITH ONLINE` is ignored and a normal index is created.

### Invisible indexes

An invisible index is maintained like any other, but the optimizer ignores it. Use this to measure the effect of an index before relying on it, or to check what happens without an index before dropping it.

```sql
CREATE INDEX idx_city_postal ON city (postal_code) INVISIBLE;
ALTER INDEX idx_city_postal ON city VISIBLE;
```


## ALTER INDEX

```text
ALTER INDEX index_name ON table_name [COMMENT 'comment'] REBUILD
ALTER INDEX index_name ON table_name COMMENT 'comment'
ALTER INDEX index_name ON table_name {VISIBLE | INVISIBLE}
```

- **REBUILD**: drop and recreate the index with the same definition, for example after many deletes. Column names given after the table name are ignored.
- **COMMENT** without `REBUILD`: change only the comment.
- **VISIBLE** | **INVISIBLE**: let the optimizer use the index, or not.

```sql
ALTER INDEX idx_product_price ON product COMMENT 'price lookups' REBUILD;
ALTER INDEX idx_product_price ON product COMMENT 'price lookups, highest first';
ALTER INDEX idx_city_postal ON city INVISIBLE;
```

An index cannot be renamed; drop it and create it again under the new name.

## DROP INDEX

```text
DROP INDEX index_name ON table_name
```

```sql
DROP INDEX idx_product_price ON product;
```

The table name is required. Indexes that belong to a constraint (primary key, unique, foreign key) are removed with [ALTER TABLE ... DROP CONSTRAINT](https://www.coradb.ai/manual/sql/schema/table_stmt.html#drop-constraint-drop-index-drop-primary-key-and-drop-foreign-key-clauses); a unique index created with `CREATE UNIQUE INDEX` can be dropped with either statement.

## See also

- [Query optimization](https://www.coradb.ai/manual/sql/tuning.html): query plans, index hints, covering indexes and other index techniques
- [CREATE TABLE](https://www.coradb.ai/manual/sql/schema/table_stmt.html#constraints): constraints and the indexes they create
- [SHOW INDEX](https://www.coradb.ai/manual/sql/query/show.html#show-index)
