![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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)
Advertisements