38

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 know 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%';
2
  • Just to note, if you are looking for instances of a character / character set, use a regex. Commented Dec 19, 2014 at 16:52
  • 1
    @JustinE - Before version 8.0, utf8 multi-byte characters were not handled correctly by REGEXP. Commented May 12, 2021 at 18:29

5 Answers 5

19

LIKE vs REGEXP in MySQL

  • Single condition: LIKE is faster
  • Multiple conditions: REGEXP is faster

Example

A real-world example could be: finding all rows containing escaped carriage returns of CRLF, LF, or CR.

Single condition

SELECT * FROM comments WHERE text LIKE '%\\\\n%'; 🚀 Faster
SELECT * FROM comments WHERE text REGEXP '\\\\n'; 🐢 Slower

Multiple conditions

SELECT * FROM comments
WHERE text LIKE '%\\\\r\\\n%'
OR text LIKE '%\\\\n%'
OR text LIKE '%\\\\r%'; 🐢 Slower

SELECT * FROM comments
WHERE text REGEXP '((\\\\r\\\\n)|(\\\\(n|r)))'; 🚀 Faster

Conclusion

Use LIKE for single condition queries, and REGEXP for multiple condition queries.

Sign up to request clarification or add additional context in comments.

Comments

16

I've tried it out on MySQL 8.0.13 and compared LIKE vs REGEXP on a table with 1M+ rows on a column with an index:

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

Query took 10.0418 seconds.

SELECT * FROM table WHERE REGEXP_LIKE(column, 'foobar');

Query took 11.0742 seconds.

LIKE performance is faster. If you can get away with using it instead of REGEXP, do it.

Comments

13

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.

Comments

6

If you can use LIKE instead of REGEXP, use LIKE

Comments

0

Better Use of LIKE Query instead of REGEXP if you are not sure about value.

Also LIKE is much faster than REGEXP.

1 Comment

Could you provide any information supporting the statement "LIKE is much faster than REGEXP"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.