MySQL query to change a string by displaying only the part of string after underscore?

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable
(
   UserName varchar(100)
);
Query OK, 0 rows affected (0.69 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('Smith_John');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('Smith_Adam');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('Smith_David');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Smith_Mike');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------------+
| UserName    |
+-------------+
| Smith_John  |
| Smith_Adam  |
| Smith_David |
| Smith_Mike  |
+-------------+
4 rows in set (0.00 sec)

Following is the query to display only the part of the string after underscore −

mysql> update DemoTable set UserName=substring(UserName,7) where UserName LIKE 'Smith_%';
Query OK, 4 rows affected (0.12 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 −

+----------+
| UserName |
+----------+
| John     |
| Adam     |
| David    |
| Mike     |
+----------+
4 rows in set (0.00 sec)
raja
Published on 27-Sep-2019 10:33:52
Advertisements