Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL LIKE vs LOCATE

Tags:

Does anyone know which one is faster:

SELECT * FROM table WHERE column LIKE '%text%'; 

or

SELECT * FROM table WHERE LOCATE('text',column)>0; 
like image 898
Ghooti Farangi Avatar asked Sep 21 '11 12:09

Ghooti Farangi


People also ask

What is locate in MySQL?

LOCATE() function in MySQL is used for finding the location of a substring in a string. It will return the location of the first occurrence of the substring in the string. If the substring is not present in the string then it will return 0.

Which is faster or like in MySQL?

1 Answer. 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.

Which is faster like or Instr?

the LIKE comparison checks the leading edge of your column, and is done. INSTR searches for the string anywhere in the column. so it makes sense that LIKE would be faster in this case - it searches less characters.

How do I find a specific word in MySQL?

LOCATE() function MySQL LOCATE() returns the position of the first occurrence of a string within a string. Both of these strings are passed as arguments. An optional argument may be used to specify from which position of the string (i.e. string to be searched) searching will start.


1 Answers

Added April 20th, 2015: Please read also Hallie's answer below


First one but marginally. Mostly because it doesn't have to do an extra > 0 comparison.

mysql> SELECT BENCHMARK(100000000,LOCATE('foo','foobar')); +---------------------------------------------+ | BENCHMARK(100000000,LOCATE('foo','foobar')) | +---------------------------------------------+ |                                           0 | +---------------------------------------------+ 1 row in set (3.24 sec)  mysql> SELECT BENCHMARK(100000000,LOCATE('foo','foobar') > 0); +-------------------------------------------------+ | BENCHMARK(100000000,LOCATE('foo','foobar') > 0) | +-------------------------------------------------+ |                                               0 | +-------------------------------------------------+ 1 row in set (4.63 sec)   mysql> SELECT BENCHMARK(100000000,'foobar' LIKE '%foo%'); +--------------------------------------------+ | BENCHMARK(100000000,'foobar' LIKE '%foo%') | +--------------------------------------------+ |                                          0 | +--------------------------------------------+ 1 row in set (4.28 sec)   mysql> SELECT @@version; +----------------------+ | @@version            | +----------------------+ | 5.1.36-community-log | +----------------------+ 1 row in set (0.01 sec) 
like image 159
Mchl Avatar answered Sep 22 '22 18:09

Mchl