MySQL query to remove text between square brackets?


Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Name text
   -> );
Query OK, 0 rows affected (0.47 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('John [John] Smith');
Query OK, 1 row affected (0.30 sec)
mysql> insert into DemoTable values('[Carol] Carol Taylor');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('David [Miller] Miller');
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output−

+-----------------------+
| Name                  |
+-----------------------+
| John [John] Smith     |
| [Carol] Carol Taylor  |
| David [Miller] Miller |
+-----------------------+
3 rows in set (0.00 sec)

Following is the query to remove text between square brackets−

mysql> select replace(Name,substring(Name,locate('[', Name), LENGTH(Name)
   -> - locate(']', reverse(Name)) - locate('[', Name) + 2), '') as Name
   -> from DemoTable;

This will produce the following output −

+---------------+
| Name          |
+---------------+
| John Smith    |
| Carol Taylor  |
| David Miller  |
+---------------+
3 rows in set (0.03 sec)

Updated on: 12-Dec-2019

705 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements