Update 'a' record with 'b' and 'b' with 'a' in a MySQL column (swap) with only 'a' and 'b' values?


For this, use a CASE statement. Let us first create a table −

mysql> create table DemoTable
(
   Value char(1)
);
Query OK, 0 rows affected (1.21 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('a');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('b');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('a');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values('a');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('b');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values('a');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('b');
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 −

+-------+
| Value |
+-------+
| a     |
| b     |
| a     |
| a     |
| b     |
| a     |
| b     |
+-------+
7 rows in set (0.00 sec)

Following is the query to update 'a' record with 'b' and 'b' with 'a' −

mysql> update DemoTable set Value=case when Value='a' then 'b' else 'a' end;
Query OK, 7 rows affected (0.17 sec)
Rows matched: 7 Changed: 7 Warnings: 0

Let us check the table records once again −

mysql> select *from DemoTable;

This will produce the following output −

+-------+
| Value |
+-------+
| b     |
| a     |
| b     |
| b     |
| a     |
| b     |
| a     |
+-------+
7 rows in set (0.00 sec)

Updated on: 25-Sep-2019

342 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements