Replace a specific duplicate record with a new value in MySQL

MySQLi DatabaseMySQL

Let us first create a table −

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Name varchar(50)
);
Query OK, 0 rows affected (0.62 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Name) values('Chris');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(Name) values('Robert');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(Name) values('Chris');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable(Name) values('David');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(Name) values('Mike');
Query OK, 1 row affected (0.13 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+--------+
| Id | Name   |
+----+--------+
|  1 | Chris  |
|  2 | Robert |
|  3 | Chris  |
|  4 | David  |
|  5 | Mike   |
+----+--------+
5 rows in set (0.00 sec)

Here is the query to replace a specific duplicate record i.e. the name “Chris” here with a new name −

mysql> update DemoTable set Name=replace(Name,'Chris','Adam Smith');
Query OK, 2 rows affected (0.17 sec)
Rows matched: 5 Changed: 2 Warnings: 0

Let us check the table records once again −

mysql> select *from DemoTable;

This will produce the following output −

+----+------------+
| Id | Name       |
+----+------------+
|  1 | Adam Smith |
|  2 | Robert     |
|  3 | Adam Smith |
|  4 | David      |
|  5 | Mike       |
+----+------------+
5 rows in set (0.00 sec)
raja
Published on 03-Oct-2019 06:33:47
Advertisements