Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is better? mysql's LIKE or REGEXP?

I have this named_scope with a LIKE and NOT LIKE in one statement. Is this faster in terms of execution compared to using REGEXP?

named_scope :order_search, :order => "name LIKE '%urgent%' AND name NOT LIKE '%not urgent%' DESC, created_at DESC"
like image 636
cancelledout Avatar asked May 27 '11 06:05

cancelledout


2 Answers

It's milliseconds difference, unnoticable. Unless you're dealing with an extremely high amount of traffic, it won't matter.

If you're experiencing performance issues with your approach, it's likely because your table has a large amount of rows. The bottle-neck isn't LIKE then (and MySQL also supports REGEXP) but your table structure.

In any case, you should read up on MySQL Indexes and MySQL Fulltext Search.

like image 80
fx_ Avatar answered Oct 07 '22 18:10

fx_


In so far as I'm aware, MySQL's LIKE will use Boyer–Moore in this case, so there might be a slight advantage for LIKE.

It'll be negligible compared to using a trigger that would store the whole expression in an is_urgent field however. You could then add an index on (is_urgent, created_at).

like image 44
Denis de Bernardy Avatar answered Oct 07 '22 18:10

Denis de Bernardy