Wednesday 18 July 2018

MySQL: Filter or Search Records Using Regular Expression

MySQL: Filter or Search Records Using Regular Expression

We can filter or search records according to the matched Regular Expression in MySQL.
For that the syntax will be
SELECT Col1, Col2, Col3   FROM   table_name   WHERE Col1 REGEXP pattern
Where Col1, Col2, Col3 is list of columns to be fetched.You can select any number of columns. Pattern is the regular expression to be matched (collection of special characters to be matched against the string values).
Below is an example how the regular expression is used for filtering or searching of specific group of records in a particular table.
For Example:
employeedetails is a table having the records as
EMP_ID   EMP_NAME
1                   John
2                   Joe
3                   Jill
4                   Jack
5                   Jojo
6                   Jo
Below are some queries and their result sets:-
SELECT e.`EMP_NAME` FROM employeedetails e
WHERE EMP_NAME  REGEXP  ‘^Jo$’;
EMP_NAME
                 Jo
SELECT e.`EMP_NAME` FROM employeedetails e
WHERE  EMP_NAME  REGEXP ‘Jo$’;
EMP_NAME
                 Jojo
                 Jo
SELECT e.`EMP_NAME` FROM employeedetails e
WHERE  EMP_NAME  REGEXP ‘^Jo’;
EMP_NAME
                 Joe
                 Jojo
       Jo
You can use your own regular expression for filtering the records.

0 comments:

Post a Comment