- 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
Swap data between two columns in MySQL?
To swap data between two columns in MySQL, use the concept of variable. Let us first create a table. Here, we will swap Name1 with Name2 −
mysql> create table DemoTable -> ( -> Name1 varchar(100), -> Name2 varchar(100) -> ); Query OK, 0 rows affected (0.58 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('John Smith','Chris Brown'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values('David Miller','Jone Doe'); Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
Output
This will produce the following output −
+--------------+-------------+ | Name1 | Name2 | +--------------+-------------+ | John Smith | Chris Brown | | David Miller | Jone Doe | +--------------+-------------+ 2 rows in set (0.00 sec)
Following is the query to swap data between two columns in MySQL −
mysql> update DemoTable -> SET Name1=(@tmpName:=Name1), Name1 = Name2, Name2 = @tmpName; Query OK, 2 rows affected (0.13 sec) Rows matched: 2 Changed: 2 Warnings: 0
Let us check table records once again −
mysql> select *from DemoTable;
Output
This will produce the following output −
+-------------+--------------+ | Name1 | Name2 | +-------------+--------------+ | Chris Brown | John Smith | | Jone Doe | David Miller | +-------------+--------------+ 2 rows in set (0.00 sec)
Advertisements