
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 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)
Advertisements