Many applications require searching for a string within a body of text. MySQL offers a LIKE operator to perform such searches, but how can we optimize these queries for optimal performance?
Consider the following table:
<code class="sql">CREATE TABLE `example` ( `id` int(11) unsigned NOT NULL auto_increment, `keywords` varchar(200) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB;</code>
When executing a query like:
<code class="sql">SELECT id FROM example WHERE keywords LIKE '%whatever%'</code>
we may expect the database to use an index to speed up the search. However, if we add a simple index on the keywords column using:
<code class="sql">ALTER TABLE `example` ADD INDEX `idxSearch` (`keywords`);</code>
an EXPLAIN query reveals that MySQL still needs to scan the entire table.
MySQL uses indexes by matching the start of the search string. For queries like LIKE 'whatever%', the index can be used because 'whatever' is anchored at the start of the string.
However, queries like LIKE '%whatever%' have no such anchor. The search term appears "floating" within the string, forcing MySQL to scan the entire field.
To optimize such queries, we can use fulltext indexes. These indexes are specifically designed for "floating" searches. InnoDB has supported fulltext indexes since version 5.6.4, making it a viable option for optimizing LIKE '%string%' queries.
The above is the detailed content of ## How Can I Optimize MySQL LIKE \'%string%\' Queries with InnoDB?. For more information, please follow other related articles on the PHP Chinese website!