I want to optimize performance of this MySQL query
SELECT * FROM (
(SELECT * FROM users USE INDEX(names) WHERE name LIKE '%leo%') UNION
(SELECT * FROM users USE INDEX(names) WHERE name LIKE '%le%') UNION
(SELECT * FROM users USE INDEX(names) WHERE name LIKE '%eo%') UNION
(SELECT * FROM users USE INDEX(names) WHERE name LIKE '%l%') UNION
(SELECT * FROM users USE INDEX(names) WHERE name LIKE '%e%') UNION
(SELECT * FROM users USE INDEX(names) WHERE name LIKE '%o%')
) as A LIMIT 5 OFFSET 5;
I want values sorted like this (leo, le, eo, l, e, o)
2
Answers
You can’t really optimize the
LIKE
condition if it begins with%
. Indexes are B-trees, so the search string has to match the beginning of the value in order to narrow it down with an index.You can use
OR
the combine all theLIKE
conditions in theWHERE
clause, and then put each condition in theORDER BY
.If you can change from
LIKE
to=
then you can simplify it to:Assuming these are just substrings in [possibly] longer names, this is the fastest because the
WHERE
clause is faster than the other suggestions.LIKE
is faster thanREGEXP
for equivalent tests. Alas, theORDER BY
cannot be optimized.