Saturday, September 27, 2008

LIKE, RLIKE, REGEXP in Mysql

LIKE in Mysql
-------------
if any expression in a string comparison is case sensitive, the comparison is performed in case-sensitive fashion.

* expr LIKE pat [ESCAPE 'escape_char']

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.

Per the SQL standard, LIKE performs matching on a per-character basis, thus it can produce results different from the = comparison operator:

With LIKE you can use the following two wildcard characters in the pattern:
Character Description
% Matches any number of characters, even zero characters
_ Matches exactly one character

mysql> SELECT 'David!' LIKE 'David_';
-> 1
mysql> SELECT 'David!' LIKE '%D%v%';
-> 1

NOT LIKE in Mysql
-----------------

expr NOT LIKE pat [ESCAPE 'escape_char']

This is the same as NOT (expr LIKE pat [ESCAPE 'escape_char']).


RLIKE, REGEXP in Mysql
----------------------

expr REGEXP pat, expr RLIKE pat

Performs a pattern match of a string expression expr against a pattern pat. The pattern can be an extended regular expression. “Regular Expressions”. Returns 1 if expr matches pat; otherwise it returns 0. If either expr or pat is NULL, the result is NULL. RLIKE is a synonym for REGEXP, provided for mSQL compatibility.

Note: REGEXP is not case sensitive, except when used with binary strings.

mysql> SELECT 'Monty!' REGEXP 'm%y%%';
-> 0
mysql> SELECT 'Monty!' REGEXP '.*';
-> 1
mysql> SELECT 'new*\n*line' REGEXP 'new\\*.\\*line';
-> 1
mysql> SELECT 'a' REGEXP 'A', 'a' REGEXP BINARY 'A';
-> 1 0
mysql> SELECT 'a' REGEXP '^[a-d]';
-> 1

REGEXP and RLIKE use the current character set when deciding the type of a character. The default is latin1

NOT RLIKE, NOT REGEXP in Mysql
------------------------------

expr NOT REGEXP pat, expr NOT RLIKE pat

This is the same as NOT (expr REGEXP pat).

No comments: