Why BINARY keyword used with MySQL REGEXP operator?


Use the BINARY keyword to force REGEXP to match the string as a binary string. We will see the difference here.

Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Name varchar(100)
   -> );
Query OK, 0 rows affected (0.46 sec)

Insert some records in the table using insert command. We have names here with different cases −

mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.18 sec)

mysql> insert into DemoTable values('JOHN');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable values('john');
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable values('JOhn');
Query OK, 1 row affected (0.17 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+------+
| Name |
+------+
| John |
| JOHN |
| john |
| JOhn |
+------+
4 rows in set (0.00 sec)

Here is the query to learn the difference between REGEXP and REGEXP operator with BINARY −

mysql> select Name REGEXP 'JOHN' AS ResultWithOutBinary, Name REGEXP BINARY 'JOHN' AS ResultWithBinary from DemoTable;

This will produce the following output −

+---------------------+------------------+
| ResultWithOutBinary | ResultWithBinary |
+---------------------+------------------+
|                   1 |                0 |
|                   1 |                1 |
|                   1 |                0 |
|                   1 |                0 |
+---------------------+------------------+
4 rows in set (0.04 sec)
raja
Published on 11-Jul-2019 17:48:21
Advertisements