Skip to content

Migrator

addIndex()

addIndex() — returns void

Available in: migration Category: Migration Functions

Adds a database index on one or more columns of a table. Indexes speed up queries that filter, sort, or join on those columns. This function is only available inside a migration CFC and is part of the Wheels migrator API.

NameTypeRequiredDefaultDescription
tablestringyesThe table name to perform the index operation on
columnNamesstringnoOne or more column names to index, comma separated
uniquebooleannofalseIf true will create a unique index constraint
indexNamestringno[runtime expression]The name of the index to add: Defaults to table name + underscore + first column name
1. Add a unique index on a single column
addIndex(
    table="members",
    columnNames="username",
    unique=true
);

Ensures username values in members are unique.

2. Add a non-unique index for faster queries
addIndex(
    table="orders",
    columnNames="createdAt"
);

Speeds up queries filtering or ordering by createdAt.

3. Add a composite index (multiple columns)
addIndex(
    table="posts",
    columnNames="authorId,createdAt"
);

Optimizes queries that filter or sort on both authorId and createdAt.

4. Add an index with a custom name
addIndex(
    table="comments",
    columnNames="postId",
    indexName="idx_comments_postId"
);

Creates index with a custom name instead of default comments_postId.

5. Composite unique index
addIndex(
    table="enrollments",
    columnNames="studentId,courseId",
    unique=true,
    indexName="unique_enrollments"
);

Prevents the same studentId and courseId pair from being inserted more than once.