If your goal is to test if a string exists in a MySQL column (of type 'varchar', 'text', 'blob', etc) which of the following is faster / more efficient / better to use, and why?
Or, is there some other method that tops either of these?
INSTR( columnname, 'mystring' ) > 0
vs
columnname LIKE '%mystring%'
They are both case-sensitive and perform full table scans. Let's create an index on the productname column. If you use the LIKE operator with the prefix search, on this indexed column, the LIKE operator will perform faster than the INSTR function.
Using '=' operator is faster than the LIKE operator in comparing strings because '=' operator compares the entire string but the LIKE keyword compares by each character of the string. We can use LIKE to check a particular pattern like column values starting with 'abc' in this case.
MySQL INSTR() Function The INSTR() function returns the position of the first occurrence of a string in another string. This function performs a case-insensitive search.
FULLTEXT searches are absolutely going to be faster, as kibibu noted in the comments above.
However:
mysql> select COUNT(ID) FROM table WHERE INSTR(Name,'search') > 0; +-----------+ | COUNT(ID) | +-----------+ | 40735 | +-----------+ 1 row in set (5.54 sec) mysql> select COUNT(ID) FROM table WHERE Name LIKE '%search%'; +-----------+ | COUNT(ID) | +-----------+ | 40735 | +-----------+ 1 row in set (5.54 sec)
In my tests, they perform exactly the same. They are both case-insensitive, and generally they perform full-table scans, a general no-no when dealing with high-performance MySQL.
Unless you are doing a prefix search on an indexed column:
mysql> select COUNT(ID) FROM table WHERE Name LIKE 'search%'; +-----------+ | COUNT(ID) | +-----------+ | 7 | +-----------+ 1 row in set (3.88 sec)
In which case, the LIKE with only a suffix wildcard is much faster.
MySQL - INSTR vs LOCATE vs LIKE vs REGEXP
For me the INSTR and LOCATE performed the fastest:
# 5.074 sec SELECT BENCHMARK(100000000,INSTR('foobar','foo')); # 5.086 sec SELECT BENCHMARK(100000000,LOCATE('foo','foobar')); # 8.990 sec SELECT BENCHMARK(100000000,'foobar' LIKE '%foo%'); # 14.433 sec SELECT BENCHMARK(100000000,'foobar' REGEXP 'foo'); # 5.5.35-0ubuntu0.12.10.2 SELECT @@version;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With