Swap a specific column value in MySQL

MySQLMySQLi Database

Let us first create a table table −

mysql> create table DemoTable1504
   -> (
   -> Id int,
   -> FirstName varchar(20)
   -> );
Query OK, 0 rows affected (0.83 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1504 values(101,'Chris');
Query OK, 1 row affected (0.63 sec)
mysql> insert into DemoTable1504 values(102,'Bob');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable1504 values(103,'David');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1504 values(104,'Mike');
Query OK, 1 row affected (0.10 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1504 ;

This will produce the following output −

+------+-----------+
| Id   | FirstName |
+------+-----------+
|  101 | Chris     |
|  102 | Bob       |
|  103 | David     |
|  104 | Mike      |
+------+-----------+
4 rows in set (0.00 sec)

Following is the query to swap a specific column value −

mysql> update DemoTable1504
   -> set FirstName='Carol'
   -> where Id=103
   -> and FirstName <> 'Carol';
Query OK, 1 row affected (0.13 sec)
Rows matched: 1  Changed: 1 Warnings: 0

Let us check the table records once again−

mysql> select * from DemoTable1504;

This will produce the following output −

+------+-----------+
| Id   | FirstName |
+------+-----------+
|  101 | Chris     |
|  102 | Bob       |
|  103 | Carol     |
|  104 | Mike      |
+------+-----------+
4 rows in set (0.00 sec)
raja
Published on 11-Dec-2019 05:58:54
Advertisements