Bug #1835 Index Not Used For Like with Expression
Submitted: 14 Nov 2003 5:17 Modified: 7 Oct 2005 21:53
Reporter: Sergei Kulakov (Candidate Quality Contributor) Email Updates:
Status: Closed Impact on me:
None 
Category:MySQL Server Severity:S4 (Feature request)
Version:3.23.58 OS:FreeBSD (Free BSD)
Assigned to: CPU Architecture:Any

[14 Nov 2003 5:17] Sergei Kulakov
Description:
When a literal not starting with '%' is given for LIKE and there is an index, the index is used, like in this query:

SELECT * FROM TradeNames WHERE TN LIKE 'A%'

which returns all strings starting with 'A'. But as soon as there is an expression, index is not used, even if the expression is obvious:

SELECT * FROM TradeNames WHERE TN LIKE CONCAT('A', '%')

There are cases when it would be convenient to make a join with like:

SELECT * FROM Table1, TradeNames 
WHERE TN LIKE Table1.SomeField

but unfortunately it is not possible

How to repeat:
On any dictionary-like table with a string field and an index on it:

[Explain] SELECT * FROM Table WHERE Name LIKE CONCAT('A', '%')

Suggested fix:
I realize that when there is an expression MySQL can't know what the expresion will evaluate for every row, hence it can't say it will use index in EXPLAIN output. But when performing the query it could first evaluate the expression and then check whether the result does not start with '%' or '_' and if not DO USE the index, probably not for every row, but at least for those that allow it. There is a table scan type 'func' and I think this is it. There are cases when you know for sure there is no '%' in data but MySQL doesn't use index anyway.
[7 Oct 2005 21:53] Hartmut Holzgraefe
not sure when exactly this was added but it works fine in 4.1.14
[10 Oct 2005 7:26] Sergei Kulakov
Yes, sure, so does it in 4.1.12.