Migrator
addIndex()
Signature
Section titled “Signature”addIndex() — returns void
Available in: migration
Category: Migration Functions
Description
Section titled “Description”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.
Parameters
Section titled “Parameters”| Name | Type | Required | Default | Description |
|---|---|---|---|---|
table | string | yes | — | The table name to perform the index operation on |
columnNames | string | no | — | One or more column names to index, comma separated |
unique | boolean | no | false | If true will create a unique index constraint |
indexName | string | no | [runtime expression] | The name of the index to add: Defaults to table name + underscore + first column name |
Examples
Section titled “Examples”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.