This SQLite post explains how to create, drop, and rename indexes in SQLite with syntax and examples.
An index is a performance-tuning method of allowing faster retrieval of records. An index creates an entry for each value that appears in the indexed columns. Each index name must be unique in the database.
You can create an index in SQLite using the CREATE INDEX statement.
The syntax to create an index in SQLite is:
It indicates that the combination of values in the indexed columns must be unique.
Optional. If specified, the CREATE INDEX statement will not raise an error if the index already exists.
The name to assign to the index.
The name of the table in which to create the index.
The columns to use in the index.
Optional. The index is sorted in ascending order for that column.
Optional. The index is sorted in descending order for that column.
A partial index is created on only a subset of the records within the table.
Let's look at an example of how to create an index in SQLite.
For example:
In this example, we've created an index on the customers table called customer_idx. It consists of only one field - the last_name field.
We could also create an index with more than one field as in the example below:
This would create an index called customer_idx that uses two columns - state and city.
To create a unique index on a table, you need to specify the UNIQUE keyword in the CREATE INDEX statement.
For example:
This example would create a unique index on the file_number field so that this field must always contains a unique value with no duplicates. This is a great way to enforce integrity within your database if you require unique values in columns that are not part of your primary key.
You could create a partial index on a table where only a subset of the records is included in the index.
For example:
Because we have included a WHERE clause, a partial index is created on only those created where the last_name is not NULL. Records where the last_name is a NULL value will not be included in the index.
You can drop an index in SQLite using the DROP INDEX statement.
The syntax to drop an index in SQLite is:
The name of the index to drop.
Optional. If specified, the DROP INDEX statement will not raise an error if the index does not exist.
Let's look at an example of how to drop an index in SQLite.
For example:
In this example, we've dropped an index called customer_idx. Because each index name must be unique within the database, we do not have to specify the table name in the DROP INDEX statement.
You can rename an index in SQLite by first dropping the index and then recreating the index with the new name.
The syntax to rename an index in SQLite is:
The name of the index that you wish to rename.
The new name for the index.
Let's look at an example of how to rename an index in SQLite.
For example:
In this example, we've renamed the index called customer_idx to customer_new_index.