How to swap a specific field value in MySQL?

MySQLi DatabaseMySQL

Let us first create a table −

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Number1 int,
   Number2 int
);
Query OK, 0 rows affected (0.68 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Number1,Number2) values(10,30);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable(Number1,Number2) values(60,50);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(Number1,Number2) values(110,100);
Query OK, 1 row affected (0.10 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+---------+---------+
| Id | Number1 | Number2 |
+----+---------+---------+
|  1 |      10 |      30 |
|  2 |      60 |      50 |
|  3 |     110 |     100 |
+----+---------+---------+
3 rows in set (0.00 sec)

Let us now swap a specific field value in MySQL. Here, we are swapping the fields “Number1” and “Number2” with Id=2 −

mysql> update DemoTable
   set Number1=(@temporaryVariable:=Number1),
   Number1=Number2,
   Number2=@temporaryVariable
   where Id=2;
Query OK, 1 row affected (0.21 sec)
Rows matched: 1 Changed: 1 Warnings: 0

Let us check the table records once again −

mysql> select *from DemoTable;

This will produce the following output −

+----+---------+---------+
| Id | Number1 | Number2 |
+----+---------+---------+
|  1 |      10 |      30 |
|  2 |      50 |      60 |
|  3 |     110 |     100 |
+----+---------+---------+
3 rows in set (0.00 sec)
raja
Published on 03-Oct-2019 07:12:52
Advertisements