Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql Improve Search Performance with wildcards (%%)

Below is a query I use for searching a person by email

  SELECT *
    FROM phppos_customers
    JOIN phppos_people ON phppos_customers.person_id = phppos_people.person_id
   WHERE deleted = 0
     AND email LIKE '%f%'
ORDER BY email ASC

Will adding an index on "email" speed up the query?

like image 310
Chris Muench Avatar asked May 05 '11 23:05

Chris Muench


People also ask

Do wildcards take longer to run?

Queries with leading wildcards generally are slow because they are not sargable. If by chance they pick up an index, they will usually full scan the index. Below is one example of a typical query that you might see when using a leading wildcard.

Does MySQL support wildcard?

MySQL WildcardsA wildcard character is used to substitute one or more characters in a string. Wildcard characters are used with the LIKE operator. The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.

What are the two wildcard characters used in MySQL?

The percentage wildcard is used to match any number of characters starting from zero (0) and more. The underscore wildcard is used to match exactly one character.


1 Answers

Wildcarding the left side of a LIKE operation ensures that an index, if one exists on the email column, can not be used.

Full Text Search (FTS) is preferred syntax for finding strings within text via SQL. MySQL has native FTS functionality, using the MATCH/AGAINST syntax (Requires the table to use the MyISAM engine for v.5.5 and below. InnoDB FTS supported on v.5.6+):

  SELECT c.*, p.*
    FROM PHPPOS_CUSTOMERS c
    JOIN PHPPOS_PEOPLE p ON p.person_id = c..person_id
   WHERE deleted = 0
     AND MATCH(email) AGAINST('f')
ORDER BY email 

But there are third party FTS technology, such as Sphinx.

like image 120
OMG Ponies Avatar answered Nov 09 '22 02:11

OMG Ponies