How to update and swap values using a query in mySQL

While Im working on a certain project, I encounter a situation where I accidentally interchange the first name and the last name. Since the entries are quite big, It’s very hard to manually swap the values one by one. So, I search the web and found out the used of temporary variable in a query. Temporary variable in a query always start with an @ symbol followed by its variable name, then := to set a value.

The Solution:
In a query we need to keep the first name in a temporary variable, and interchange the last name and first name then get the last name from our temporary variable. Check the solution below:

UPDATE `user` SET `fname`=@tmp:=`fname`, `fname`=`lname`, `lname`=@tmp WHERE your_condition

Above is the final output of the solution, where the first name and last name swap successfully. Obviously there are other way to do it and you can freely share it using comment! Thank you!

By erwinbantilan

I'm a Freelance Web Developer (PHP, Flash, Ajax, Javascript, CSS & HTML 4/5), iOS Developer, SEO expert and a Graphic Designer from General Santos City. Freelancer.com Profile | Libnary.com | Pattern Lockscreen

1 comment

Leave a comment

Your email address will not be published. Required fields are marked *

%d bloggers like this: