Swap column values in Mysql

As we know MySql is one of the popular databases used these days, we would be discussing about one issue I faced recently and thought to share the solution for someone facing the same issue, swap column values in MySql.

I was trying to insert profile id and userid into a table but, by mistake, I inserted profileid into userid, since table was having thousands of records, thinking of changing every row was a difficult task. I found an easier solution, instead of changing rows value, I thought to Swap Column values and I did it, just by using simple MySql query.


Idea is to use a temporary variable to store values temporally and swap them. Below is how, we can achieve this:

UPDATE TABLE_NAME SET userid =(@temporary:= userid), userid = profileid, profileid = @ temporary;

Above query will swap values of two columns and you don’t need to worry about rows.

Hope this post help you guyz. If you found this post helpful do hit the like button and share with others.



“I am PHP Freelancer having more than 7 years of experience, if you want to do any project with me then you can contact me.”

Be Social, Share!