Home > Database > Mysql Tutorial > ## How Can I Optimize MySQL LIKE \'%string%\' Queries with InnoDB?

## How Can I Optimize MySQL LIKE \'%string%\' Queries with InnoDB?

Linda Hamilton
Release: 2024-10-25 06:22:02
Original
709 people have browsed it

## How Can I Optimize MySQL LIKE '%string%' Queries with InnoDB?

Optimizing MySQL LIKE '%string%' Queries in InnoDB

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?

Problem

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>
Copy after login

When executing a query like:

<code class="sql">SELECT id FROM example WHERE keywords LIKE '%whatever%'</code>
Copy after login

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>
Copy after login

an EXPLAIN query reveals that MySQL still needs to scan the entire table.

Solution

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template