Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between like and regex operator

I'm learning MySQL now. I need your help in understanding the difference between these queries:

select id from tab where id like '000';

select id from tab where id regex '000';
like image 516
user494841 Avatar asked Nov 02 '10 14:11

user494841


3 Answers

Your first query uses like operator but does not use any wildcards. So it's equivalent to:

select id from tab where id = '000';

which lists only those id's where id is 000.

The second query uses regex operator and it lists rows where id has 000 anywhere in it.

Example: It'll list these id's: 1000,2000,000,0001

To make your first query behave like the second you'll have to use wild card % which matches zero or more characters:

select id from tab where id like '%000%';

To make your second query behave like the fist you'll have to use start anchor(^) and end anchor($):

select id from tab where id regex '^000$';
like image 64
codaddict Avatar answered Oct 18 '22 22:10

codaddict


Just in case you meant the first statement to be:

select id from tab where id like '%000%';

That means: anything (or nothing), followed by '000', followed by anything (or nothing).

This happens to be just what id regex '000' does.

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. Have fun.

like image 21
egrunin Avatar answered Oct 18 '22 21:10

egrunin


The like operator allows for specifying wildcards using the % operator.

If for instance you need to specify all words starting with the character a, you can do so by using the value "a%". You could also specify words ending with a string of characters. E.g. words ending with ing can be specified using "%ing"

You could also have parameters specifying columns containing values that contain a certain string. E.g. words that contain the characters fish can be specified using the like parameter "%fish%"

Regexp (I don't think there's a regex operator) on the other hand allows you to specify regular expression in comparing values in a column with a parameter. For instance, if you need to retrieve all records that match a phone number in the format 555-666-7777 you can use the parameter "[[:digit:]]{3}\-[[:digit:]]{3}\-[[:digit:]]{4}"

E.g. SELECT * FROM phonebook WHERE phone REGEXP "[[:digit:]]{3}\-[[:digit:]]{3}\-[[:digit:]]{4}"

Please see http://dev.mysql.com/doc/refman/5.1/en/regexp.html for more information on the REGEXP operator.

like image 1
takinbo Avatar answered Oct 18 '22 22:10

takinbo