Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL | REGEXP VS Like

I have a table CANDIDATE in my db which is running under MySQL 5.5 and I am trying to get rows from table where RAM is contains in firstname, so I can run below two queries, but I would like to now which query we should use for long term with respect to optimization.

SELECT * FROM CANDIDATE c WHERE firstname REGEXP 'ram'; SELECT * FROM CANDIDATE c WHERE firstname LIKE'%ram%'; 
like image 668
Vardan Gupta Avatar asked May 20 '13 09:05

Vardan Gupta


People also ask

Is REGEXP faster than like?

Also LIKE is much faster than REGEXP.

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 like or Rlike faster?

While neither of these operations (suffix matching) could leverage table indices, the LIKE operator ran 5-6 times faster than the RLIKE / REGEXP operator to find the same data.

What is the difference between like and regex operators in MySQL?

Basically, LIKE does very simple wildcard matches, and REGEX is capable of very complicated wildcard matches. In fact, regular expressions ( REGEX ) are so capable that they are [1] a whole study in themselves [2] an easy way to introduce very subtle bugs.


Video Answer


1 Answers

REGEXP and LIKE are used to totally different cases.

LIKE is used to add wildcards to a string whereas REGEXP is used to match an attribute with Regular Expressions.

In your case a firstname is more likely to be matched using LIKE than REGEXP and hence, it will be more optimized.

like image 176
draxxxeus Avatar answered Sep 22 '22 21:09

draxxxeus