How to update a MySQL table by swapping two column values?


To swap two values in a column, use CASE WHEN statement. Let us first create a table −

mysql> create table DemoTable1382
   -> (
   -> StudentName varchar(20)
   -> );
Query OK, 0 rows affected (0.57 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1382 values('John');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1382 values('Chris');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1382 values('Adam');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1382 values('Bob');
Query OK, 1 row affected (0.17 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1382;

This will produce the following output −

+-------------+
| StudentName |
+-------------+
| John        |
| Chris       |
| Adam        |
| Bob         |
+-------------+
4 rows in set (0.00 sec)

Following is the query to update a MySQL table by swapping two column values −

mysql> update DemoTable1382
   ->  set StudentName=( case when StudentName="Chris" then "John"
   -> when StudentName="John" then "Chris"
   -> else
   -> StudentName
   -> end
   -> );
Query OK, 2 rows affected (0.19 sec)
Rows matched: 4  Changed: 2 Warnings: 0

Let us check the table records once again −

mysql> select * from DemoTable1382;

This will produce the following output −

+-------------+
| StudentName |
+-------------+
| Chris       |
| John        |
| Adam        |
| Bob         |
+-------------+
4 rows in set (0.00 sec)

Updated on: 11-Nov-2019

314 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements