20

is there anyway to speed up mysql like operator performance if wild card is involved? eg. like '%test%'

MPelletier
  • 16,256
  • 15
  • 86
  • 137
user121196
  • 30,032
  • 57
  • 148
  • 198

2 Answers2

27

MySQL can use an index if your query looks like foo LIKE 'abc%' or foo LIKE 'abc%def%'. It can use the index for any portion or the string before the first wildcard. If you need to match a word anywhere within a string, you might want to consider using FULLTEXT indexes instead.

More detail on indexes: http://dev.mysql.com/doc/refman/5.1/en/mysql-indexes.html

Full text search: http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html

Cal
  • 7,067
  • 25
  • 28
  • essentially, if you index a column with B+ Tree index, that's sufficient. Automatically MySql searches faster for LIKE queries – Antony Dec 07 '11 at 11:53
5

Well, the simplest optimization would be to have a constant prefix (e.g. "test%" instead of "%test" or "%test%") since that would allow the engine to narrow down the search space using indices. However, that is not possible in all situations.

Sometimes a preprocessing step can turn a wildcard search into an ordinary equality or a fulltext search. You'll gain more by finding a way to structure your data so that it does not require a wildcard search than trying to optimize the latter.

Max Shawabkeh
  • 37,799
  • 10
  • 82
  • 91