Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is faster — INSTR or LIKE?

Tags:

mysql

sql-like

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%' 
like image 517
Grekker Avatar asked Mar 16 '10 01:03

Grekker


People also ask

Is Instr faster than like?

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.

What is faster than like?

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.

What is Instr in MySQL?

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.


2 Answers

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.

like image 124
razzed Avatar answered Sep 28 '22 02:09

razzed


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; 
like image 28
pdolinaj Avatar answered Sep 28 '22 01:09

pdolinaj