[SOLVED] Run a rails query in batches


I have a table A(:name, :address, :phone) consisting of 500,000 entries. I want to run this query :

johns = A.where(:name => "John")

This query should return 150,000 results. But running this query gives me this result : Killed.

How should I rewrite this query so that the query runs on batches of 1000 in the database?


You need to use find_each with the option batch_size.

A.where(:name => "John").find_each(batch_size: 1000) do |a|
  # your code

Answered By – Arup Rakshit

Answer Checked By – Marie Seifert (BugsFixing Admin)

Leave a Reply

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