Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case sensitive RLIKE

Tags:

regex

mysql

Consider a table datatbl like this:

+----------+
| strfield |
+----------+
|    abcde |
|    fgHIJ |
|    KLmno |
+----------+

I want to write a query something like this:

select * from datatbl where strfield rlike '[a-z]*';

As in a non-SQL regex, I'd like to return the lowercase row with abcde, but not the rows with capitals. I cannot seem to find an easy way to do this. Am I missing something stupid?

like image 807
Joe Mastey Avatar asked Jun 30 '10 22:06

Joe Mastey


People also ask

Is Rlike case-sensitive?

The RLIKE condition performs a case-insensitive match, except when used with binary strings.

Is Rlike case-sensitive in SQL?

REGEXP is not case sensitive, except when used with binary strings. It seems to be very sure about that REGEXP without any modifiers will select rows in case insensitive mode.

Is SQL wildcard case-sensitive?

SQL keywords are by default set to case insensitive, which means that the keywords are allowed to be used in lower or upper case. The names of the tables and columns specification are set to case insensitive on the SQL database server; however, it can be enabled and disabled by configuring the settings in SQL.

Is MySQL case-sensitive like?

By default, it depends on the operating system and its case sensitivity. This means MySQL is case-insensitive in Windows and macOS, while it is case-sensitive in most Linux systems. However, you can change the behavior by changing collation.


3 Answers

The MySQL REGEXP/RLIKE sucks for this - you need to cast the data as BINARY for case sensitive searching:

SELECT * 
  FROM datatbl 
 WHERE CAST(strfield  AS BINARY) rlike '[a-z]*';

You'll find this raised in the comments for the REGEXP/RLIKE documentation.

like image 177
OMG Ponies Avatar answered Oct 07 '22 20:10

OMG Ponies


Edit: I've misread OP and this is solution for the opposite case where MySQL is in SENSITIVE collation and you need to compare string in INSENSITIVE way.

MySQL 5.x

You can workaround it using LOWER() function, too.

SELECT * 
FROM datatbl 
WHERE LOWER(strfield) RLIKE '[a-z]*';

MySQL 8+

If you are running MySQL 8+, you can also use case-insensitive switch in REGEXP_LIKE() function.

SELECT * 
FROM datatbl 
WHERE REGEXP_LIKE(strfield, '[a-z]*', 'i');
like image 34
CraZ Avatar answered Oct 07 '22 20:10

CraZ


For case-sensitive regex you can use REGEXP_LIKE() with match type c like this:

SELECT * FROM `table` WHERE REGEXP_LIKE(`column`, 'value', 'c');
like image 35
Eaten by a Grue Avatar answered Oct 07 '22 19:10

Eaten by a Grue