Question: I need to update a table data in database using RAILS migrations. 

```
Sample:
Table: Table_A(Col_A(number), Col_B(varchar),...)
Query: UPDATE Table_A SET Col_B = "XXX" where Col_B = "YYY"

```

What would be the best way to do this using RAILS Migrations. I am not even sure if RAILS migrations is the way to go for updating data in database. Any explanation would be helpful.

Answer: 
It's usually better to do these sorts of big data updates in a rake task. I usually write them so they have two versions: rake change\_lots\_of\_data:report and rake change\_lots\_of\_data:update. The 'report' version just executes the where clause and spits out a list of what would be changed. The 'update' version uses the very same where clause but makes the changes.

Some advantages of doing it this way are:

* Migrations are saved for changing the database structure
* You can run the 'report' version as often as you want to make sure the right records are going to be updated.
* It's easier to unit test the class called by the rake task.
* If you ever need to apply the same criteria to make the change again, you can just run the rake task again. It's possible but trickier to do that with migrations.
I prefer to do any database data changes in a rake task so that's it's

1. Obvious
2. Repeatable
3. Won't later be executed via `rake db:migrate`

The code:

```
namespace :update do
  desc "Update table A to set Col_B to YYY"
    task :table_a => :environment do
      TableA.where(Col_B: "YYY").update_all(Col_B: "XXX")
    end
  end
end

```

Then you can `rake update:table_a` to execute the update.