Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql Not Like Regexp?

I'm trying to find rows where the first character is not a digit. I have this:

SELECT DISTINCT(action) FROM actions 
WHERE qkey = 140 AND action NOT REGEXP '^[:digit:]$';

But, I'm not sure how to make sure it checks just the first character...

like image 893
TwixxyKit Avatar asked Apr 05 '10 16:04

TwixxyKit


People also ask

Can we use not with REGEXP in SQL?

In MySQL, NOT REGEXP is a negation of the REGEXP operator. In other words, if the string matches the regular expression provided, the result is 0 , otherwise it's 1 . This is the opposite result to what the REGEXP would return (when it isn't prefixed with NOT ).

What is the difference between like and REGEXP 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.

What is not like in MySQL?

MySQL NOT LIKE is used to exclude those rows which are matching the criterion followed by LIKE operator. Pattern matching using SQL simple regular expression comparison. Returns 1 (TRUE) or 0 (FALSE). If either expr or pat is NULL, the result is NULL.

Can we use REGEXP in MySQL?

MySQL supports another type of pattern matching operation based on the regular expressions and the REGEXP operator. It provide a powerful and flexible pattern match that can help us implement power search utilities for our database systems. REGEXP is the operator used when performing regular expression pattern matches.


1 Answers

First there is a slight error in your query. It should be:

NOT REGEXP '^[[:digit:]]'

Note the double square parentheses. You could also rewrite it as the following to avoid also matching the empty string:

REGEXP '^[^[:digit:]]'

Also note that using REGEXP prevents an index from being used and will result in a table scan or index scan. If you want a more efficient query you should try to rewrite the query without using REGEXP if it is possible:

SELECT DISTINCT(action) FROM actions 
WHERE qkey = 140 AND action < '0'
UNION ALL
SELECT DISTINCT(action) FROM actions 
WHERE qkey = 140 AND action >= ':'

Then add an index on (qkey, action). It's not as pleasant to read, but it should give better performance. If you only have a small number of actions for each qkey then it probably won't give any noticable performance increase so you can stick with the simpler query.

like image 115
Mark Byers Avatar answered Sep 21 '22 08:09

Mark Byers