How to remove -XXX from Zip Code field using MySQL REGEXP?


The easiest way to achieve this is by using the MySQL SUBSTRING_INDEX() function. Let us first create a table −

mysql> create table DemoTable
(
   ZipCode varchar(50)
);
Query OK, 0 rows affected (2.02 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('52533-909');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values('12345-674');
Query OK, 1 row affected (0.27 sec)
mysql> insert into DemoTable values('89893-890');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable values('AAAAA-783');
Query OK, 1 row affected (0.25 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+
| ZipCode   |
+-----------+
| 52533-909 |
| 12345-674 |
| 89893-890 |
| AAAAA-783 |
+-----------+
4 rows in set (0.00 sec)

Following is the query to remove -XXX from zipcode using substring_index() −

mysql> update DemoTable set ZipCode=substring_index(ZipCode, '-', 1);
Query OK, 4 rows affected (0.44 sec)
Rows matched : 4 Changed : 4 Warnings : 0

Let us check the table records once again −

mysql> select *from DemoTable;

This will produce the following output −

+---------+
| ZipCode |
+---------+
| 52533   |
| 12345   |
| 89893   |
| AAAAA   |
+---------+
4 rows in set (0.00 sec)

Updated on: 09-Oct-2019

98 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements