love2code love2code - 21 days ago 5
MySQL Question

How to copy one column's value to another before updating

I am runnning a Postgres and Mysql server and I have table:

id | name | age | old_age
1 abc 20


I want to update column age with 21 with storing old value 20 into old_age column.
I can fetch the row and read the value of age and then update but that will require running 2 queries. 1 select and 1 update. Is there any way we can update in 1 query? I just want to copy age to old_age.

Answer

Just do

UPDATE TableName SET old_age=age, age=21 WHERE 
Comments