MySQL query to update every alternative row string having same values?

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Subject varchar(100)
   -> );
Query OK, 0 rows affected (0.76 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Subject) values('C');
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable(Subject) values('MongoDB');
Query OK, 1 row affected (0.21 sec)

mysql> insert into DemoTable(Subject) values('Java');
Query OK, 1 row affected (0.18 sec)

mysql> insert into DemoTable(Subject) values('MongoDB');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable(Subject) values('Python');
Query OK, 1 row affected (0.19 sec)

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

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+----+---------+
| Id | Subject |
+----+---------+
| 1  | C       |
| 2  | MongoDB |
| 3  | Java    |
| 4  | MongoDB |
| 5  | Python  |
| 6  | MongoDB |
+----+---------+
6 rows in set (0.00 sec)

Here is the query to update every second row string −

mysql> update DemoTable set Subject=replace(Subject,'MongoDB','MySQL') where Id%2=0;
Query OK, 3 rows affected (0.17 sec)
Rows matched: 3 Changed: 3 Warnings: 0

Let us check all records from the table −

mysql> select *from DemoTable;

Output

+----+---------+
| Id | Subject |
+----+---------+
| 1  | C       |
| 2  | MySQL   |
| 3  | Java    |
| 4  | MySQL   |
| 5  | Python  |
| 6  | MySQL   |
+----+---------+
6 rows in set (0.00 sec)
raja
Published on 09-Jul-2019 11:41:15
Advertisements