|
| 1 | +# New features |
| 2 | + |
| 3 | +## `USE INDEX`, `FORCE INDEX` and `IGNORE INDEX` for MySQL |
| 4 | + |
| 5 | +In MySQL, the statements USE INDEX, FORCE INDEX, and IGNORE INDEX are hints used in SQL queries to influence how the query optimizer selects indexes. These hints provide fine-grained control over index usage, helping optimize performance when the default behavior of the optimizer is not ideal. |
| 6 | + |
| 7 | +### Use Index |
| 8 | + |
| 9 | +The `USE INDEX` hint suggests to the optimizer which indexes to consider when processing the query. The optimizer is not forced to use these indexes but will prioritize them if they are suitable. |
| 10 | + |
| 11 | +```ts |
| 12 | +export const users = mysqlTable('users', { |
| 13 | + id: int('id').primaryKey(), |
| 14 | + name: varchar('name', { length: 100 }).notNull(), |
| 15 | +}, () => [usersTableNameIndex]); |
| 16 | + |
| 17 | +const usersTableNameIndex = index('users_name_index').on(users.name); |
| 18 | + |
| 19 | +await db.select() |
| 20 | + .from(users, { useIndex: usersTableNameIndex }) |
| 21 | + .where(eq(users.name, 'David')); |
| 22 | +``` |
| 23 | + |
| 24 | +### Ignore Index |
| 25 | + |
| 26 | +The `IGNORE INDEX` hint tells the optimizer to avoid using specific indexes for the query. MySQL will consider all other indexes (if any) or perform a full table scan if necessary. |
| 27 | + |
| 28 | +```ts |
| 29 | +export const users = mysqlTable('users', { |
| 30 | + id: int('id').primaryKey(), |
| 31 | + name: varchar('name', { length: 100 }).notNull(), |
| 32 | +}, () => [usersTableNameIndex]); |
| 33 | + |
| 34 | +const usersTableNameIndex = index('users_name_index').on(users.name); |
| 35 | + |
| 36 | +await db.select() |
| 37 | + .from(users, { ignoreIndex: usersTableNameIndex }) |
| 38 | + .where(eq(users.name, 'David')); |
| 39 | +``` |
| 40 | + |
| 41 | +### Force Index |
| 42 | + |
| 43 | +The `FORCE INDEX` hint forces the optimizer to use the specified index(es) for the query. If the specified index cannot be used, MySQL will not fall back to other indexes; it might resort to a full table scan instead. |
| 44 | + |
| 45 | +```ts copy |
| 46 | +export const users = mysqlTable('users', { |
| 47 | + id: int('id').primaryKey(), |
| 48 | + name: varchar('name', { length: 100 }).notNull(), |
| 49 | +}, () => [usersTableNameIndex]); |
| 50 | + |
| 51 | +const usersTableNameIndex = index('users_name_index').on(users.name); |
| 52 | + |
| 53 | +await db.select() |
| 54 | + .from(users, { forceIndex: usersTableNameIndex }) |
| 55 | + .where(eq(users.name, 'David')); |
| 56 | +``` |
| 57 | + |
| 58 | +You can also combine those hints and use multiple indexes in a query if you need |
0 commit comments