Home > Database > Mysql Tutorial > body text

## MySQL LIKE vs LOCATE: Which is Faster for Pattern Matching?

DDD
Release: 2024-10-25 01:52:30
Original
783 people have browsed it

##  MySQL LIKE vs LOCATE: Which is Faster for Pattern Matching?

MySQL LIKE vs LOCATE: Which is More Efficient?

When performing pattern matching queries in MySQL, you have two main options: the LIKE operator and the LOCATE function. Which one performs faster?

To answer this question, let's compare the performance of these two approaches using a simple benchmark. The following query uses the LIKE operator to find rows where a column contains a specific text:

SELECT * FROM table WHERE column LIKE '%text%';
Copy after login

The following query uses the LOCATE function to perform the same operation:

SELECT * FROM table WHERE LOCATE('text',column)>0;
Copy after login

Running these queries against a large dataset shows that the LIKE operator is marginally faster, primarily because it avoids the additional comparison (> 0) required by LOCATE. Here are the results from a benchmark:

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)
Copy after login

The above is the detailed content of ## MySQL LIKE vs LOCATE: Which is Faster for Pattern Matching?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!