MySQL regular expression to update a table with column values including string, numbers and special characters


For this, use UPDATE command along with REGEXP. Let us first create a table −

mysql> create table DemoTable2023
   -> (
   -> StreetNumber varchar(100)
   -> );
Query OK, 0 rows affected (0.59 sec)

Insert some records in the table using insert command −

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

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

mysql> insert into DemoTable2023 values('AUS-100');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable2023 values('US-101');
Query OK, 1 row affected (0.11 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable2023;

This will produce the following output −

+--------------+
| StreetNumber |
+--------------+
| 7            |
| 1            |
| AUS-100      |
| US-101       |
+--------------+
4 rows in set (0.00 sec)

Here is the query to update a table using a regular expression −

mysql> update DemoTable2023
   -> set StreetNumber=concat('Street',StreetNumber)
   -> where StreetNumber regexp'^[0-9]{1,2}$';
Query OK, 2 rows affected (0.19 sec)
Rows matched: 2 Changed: 2 Warnings: 0

Let us check the table records once again −

mysql> select *from DemoTable2023;

This will produce the following output −

+--------------+
| StreetNumber |
+--------------+
| Street7      |
| Street1      |
| AUS-100      |
| US-101       |
+--------------+
4 rows in set (0.00 sec)

Updated on: 06-Apr-2020

528 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements