Documentation

Indexes

Home · Русский

Indexes when creating a table

The i flag creates an index on a column:

db.create_table(
    "players",
    ("p", "id", int),
    ("un", "login", str),
    ("i", "level", int),
)

create_table() avoids redundant indexes: if the same column has a PRIMARY KEY (p) or UNIQUE (u) constraint, no separate index is created for i. For example, "ui" does not create an additional non-unique index.

This check applies only when creating the table. Calling create_table() again for an existing table does not add indexes, even if its definition has changed.

Managing indexes

Method Effect
create_index(table_name, column_name, *, flexible=False) Index a column or a flexible field with flexible=True.
remove_index(table_name, column_name) Remove the index with the name generated by LiteCrate; a missing index is allowed.
get_table_indexes(table_name) Return a sorted list of index names for the table.
db.create_index("players", "level")

print(db.get_table_indexes("players"))
# ['idx_78d030432d37cc35775d8d2e012ac858']

db.remove_index("players", "level")

Important: create_index() does not check whether an index is needed. It can create an index even on a column already indexed through UNIQUE or PRIMARY KEY.

Also, create_index() uses a plain CREATE INDEX statement: if an index with the generated name already exists, SQLite raises an error. Unlike remove_index(), this operation is not designed to be repeated without errors.

get_table_indexes() excludes the automatic indexes SQLite creates for UNIQUE and PRIMARY KEY constraints. Removing a LiteCrate index does not remove those constraints.

If the schema is known in advance, it is usually more convenient to declare an index using the i flag in create_table().

Flexible field indexes

In a table created with flexible=True, you can index an extra top-level field. SQLite can use the index when a filter or sort matches the indexed expression.

db.create_index("players", "nickname", flexible=True)
player = db.select_one("players", "nickname = ?", "Pilot")
db.remove_index("players", "nickname")

You can add the index to an existing flexible table. SQLite stores it separately and maintains it on writes. get_table_indexes() lists flexible field indexes, and rename_table() carries them over under the new table name.