14

In MySql, I want to locate records where the string value in one of the columns begins with (or is the same as) a query string. The column is indexed with the appropriate collation order. There is no full-text search index on the column though.

A good solution will:

  1. Use the index on the column. Solutions that need to iterate over all the records in the table aren't good enough (several million records in the table)

  2. Work with strings with any character values. Some of the column values contain punctuation characters. The query string might too. Keep this in mind if your solution includes regex characters or similar. The strings are UTF-8 encoded, but if your solution only works with ASCII it could still be useful.

The closest I have at this point is

SELECT * FROM TableName WHERE ColumnName BETWEEN query AND <<query+1>>

Where <<query+1>> is pre-computed to lexicographically follow query in the collation order. For example, if query is "o hai" then <<query+1>> is "o haj".

2 Answers 2

32

Surprisingly, a LIKE query will use an index just fine if you're doing a prefix search.

SELECT * from TableName Where ColumnName LIKE 'o hai%'

will indeed use an index since it does not begin with a wildcard character.

This (and other behavior) is documented in the "How MySQL uses Indexes" doc: http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html

You will need to escape the '%' character and follow normal quoting rules, but other than that any utf-8 input prefix ought to work and do the job. Run an EXPLAIN query to make sure, sometimes other reasons can preclude indexes from working such as needing to do an OPTIMIZE TABLE to update index cardinalities (though this can take ages and locks your table)

2
  • Perfect -- thanks. EXPLAIN indeed indicates a range query. The MySql docs for LIKE indicate only the following characters need to be escaped: '%', '_': dev.mysql.com/doc/refman/5.0/en/…. Jan 6, 2010 at 7:19
  • I might mention that in the case index cardinalities do need to be updated, ANALYZE TABLE is in theory faster than OPTIMIZE TABLE. The table is still locked for write during this time, though. Running ANALYZE TABLE on a table of mine with ~6 million rows took a good hour.
    – Crast
    Jan 6, 2010 at 7:39
5

Try this:

SELECT * FROM tablename WHERE columname LIKE CONCAT(query, '%');
2
  • 3
    That would work great until query has a % or a _ in it. They need to be escaped.
    – AndrewF
    Feb 19, 2016 at 4:05
  • the '\\' also need be escaped
    – lidaobing
    Apr 30, 2019 at 2:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.