How to update data in a MySQL database without removing the old data?

MySQLMySQLi Database

For this, you can use UPDATE and concatenate the new data with the old one to save the old data as well −

update yourTableName set yourColumnName=concat(yourColumnName,",yourValue");

Let us first create a table −

mysql> create table DemoTable
-> (
-> CustomerName varchar(100)
-> );
Query OK, 0 rows affected (0.54 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('Chris');
Query OK, 1 row affected (0.24 sec)

mysql> insert into DemoTable values('David');
Query OK, 1 row affected (0.16 sec)

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

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

This will produce the following output −

+--------------+
| CustomerName |
+--------------+
| Chris        |
| David        |
| Sam          |
+--------------+
3 rows in set (0.00 sec)

Following is the query to update new data in the database without removing old data −

mysql> update DemoTable set CustomerName=concat(CustomerName,",Brown");
Query OK, 3 rows affected (0.14 sec)
Rows matched: 3 Changed: 3 Warnings: 0

Let us check the table records once again −

mysql> select *from DemoTable;

Output

This will produce the following output −

+--------------+
| CustomerName |
+--------------+
| Chris,Brown  |
| David,Brown  |
| Sam,Brown    |
+--------------+
3 rows in set (0.00 sec)
raja
Published on 11-Jul-2019 12:46:53
Advertisements