How to change a specific char in a MySQL string?

MySQLMySQLi Database

To change a specific char in a MySQL string, you can use CONCAT() along with SUBSTRING().

Let us first create a table −

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Value varchar(200)
);
Query OK, 0 rows affected (0.60 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Value) values('98764');
Query OK, 1 row affected (0.17 sec)

Following is the query to display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+-------+
| Id | Value |
+----+-------+
| 1  | 98764 |
+----+-------+
1 row in set (0.00 sec)

Here is the query to change a specific char in a MySQL string. We have set X here where 6 was placed −

mysql> select concat(substring(Value,1,3),'X',substring(Value,5)) from DemoTable;

This will produce the following output −

+-----------------------------------------------------+
| concat(substring(Value,1,3),'X',substring(Value,5)) |
+-----------------------------------------------------+
| 987X4                                               |
+-----------------------------------------------------+
1 row in set (0.00 sec)
raja
Published on 29-Apr-2019 14:51:02
Advertisements