Computer >> Computer tutorials >  >> Programming >> MySQL

Select query with regular expression in MySQL


Let us first create a table −

mysql> create table DemoTable1573
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentCode varchar(20)
   -> );
Query OK, 0 rows affected (0.63 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1573(StudentCode) values('STU_774');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1573(StudentCode) values('909_Sam');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1573(StudentCode) values('3_Carol_455');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1573(StudentCode) values('David_903');
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1573;

This will produce the following output −

+-----------+-------------+
| StudentId | StudentCode |
+-----------+-------------+
|         1 | STU_774     |
|         2 | 909_Sam     |
|         3 | 3_Carol_455 |
|         4 | David_903   |
+-----------+-------------+
4 rows in set (0.00 sec)

Here is the query to implement select query with regular expression −

mysql> select * from DemoTable1573 where StudentCode regexp '\land[0-9]';

This will produce the following output −

+-----------+-------------+
| StudentId | StudentCode |
+-----------+-------------+
|         2 | 909_Sam     |
|         3 | 3_Carol_455 |
+-----------+-------------+
2 rows in set (0.14 sec)