Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance of RegEx vs LIKE in MySql queries

Tags:

mysql

Rumour has it that this:

SELECT * FROM lineage_string where lineage like '%179%' and  lineage regexp '(^|/)179(/|$)' 

Would be faster than this:

SELECT * FROM lineage_string where lineage regexp '(^|/)179(/|$)' 

Can anyone confirm? Or know a decent way to test the speed of such queries. Thanks

like image 718
Tim Avatar asked Apr 29 '10 19:04

Tim


People also ask

Is regex faster than like in SQL?

Yeah, it probably would be a tiny bit faster because standard-SQL LIKE is a simpler comparison operation than a full-on regex parser. However, in real terms both are really slow, because neither can use indices. ( LIKE can use an index if the match string doesn't start with a wildcard, but that's not the case here.)

Is regex faster than like?

Also LIKE is much faster than REGEXP.

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 queries are faster in MySQL?

MySQL full-text search (FTS) is far much faster than queries using wildcard characters.


2 Answers

It is possible that it could be faster because the LIKE condition can be evaluated more quickly then the regular expression so if most rows fail the test it could be faster. However it will be slower if most rows succeed as two tests must be run for successful rows instead of just one. It also depends on which expression the optimizer chooses to run first.

An even bigger speedup can be witnessed if you have something like this:

SELECT * FROM (    SELECT * FROM lineage_string    WHERE lineage LIKE '179%' ) WHERE lineage regexp '^179(/|$)' 

Now an index can be used to find likely rows because LIKE '179%' is sargable. Many rows won't need to be checked at all.

As always the best way to be sure is to measure it for yourself on your actual data.

like image 158
Mark Byers Avatar answered Sep 16 '22 20:09

Mark Byers


Yeah, it probably would be a tiny bit faster because standard-SQL LIKE is a simpler comparison operation than a full-on regex parser.

However, in real terms both are really slow, because neither can use indices. (LIKE can use an index if the match string doesn't start with a wildcard, but that's not the case here.)

If you are concerned about speed, you should change your schema so that you can put the 179 directly in a column and index it, rather than having to check through a string manually on every row.

like image 38
bobince Avatar answered Sep 17 '22 20:09

bobince