overburn overburn - 5 months ago 7
SQL Question

Like query performance on medium table (~3m records)

I have a small problem. I have a table of about 3m cities, and I need to run a

like
query on it.

The thing is, it takes about 9s to complete the query. Any ideas how I could make it very fast?

The query is:

SELECT * FROM `cities` WHERE name LIKE '%test%'

Answer

try to use a FULLTEXT INDEX. InnoDB now also has FULLTEXT INDEX.

CREATE FULLTEXT INDEX idx_name_ft ON cities  (`name`);

and use like this:

SELECT * FROM cities WHERE MATCH(`name`) AGAINST('test');

sample

i have create a easy sample table with 5000000 row and this it my result:

MariaDB [yourschema]> SELECT * FROM cities WHERE `name` LIKE '%test%';
+---------+------------------------------------------------------+
| id      | name                                                 |
+---------+------------------------------------------------------+
|       7 | name of the city is test more text here              |
|    1096 | name of the city is other more text here - test      |
|    1109 | test name of the city is other more text here        |
| 4998932 | name of the city is other more text here - last test |
| 4999699 | name of the city is other more text here - test some |
| 4999997 | name of the city is - test again - more text here    |
+---------+------------------------------------------------------+
6 rows in set (4.29 sec)

MariaDB [yourschema]> SELECT * FROM cities WHERE MATCH(`name`) AGAINST('test');
+---------+------------------------------------------------------+
| id      | name                                                 |
+---------+------------------------------------------------------+
|       7 | name of the city is test more text here              |
|    1096 | name of the city is other more text here - test      |
|    1109 | test name of the city is other more text here        |
| 4998932 | name of the city is other more text here - last test |
| 4999699 | name of the city is other more text here - test some |
| 4999997 | name of the city is - test again - more text here    |
+---------+------------------------------------------------------+
6 rows in set (0.60 sec)

MariaDB [yourschema]>
Comments