Skip to main content

Rails find_each vs each

each loads every matching row into memory with one query. find_each loads rows in batches, 1000 by default, and walks the primary key. Use find_each for large tables and each for small ones you will load anyway.

Tested on Rails 8.1.1 and PostgreSQL 16, . Every example below ran, and the generated SQL is the SQL Rails sent.

The conversion

SQL

SELECT * FROM posts ORDER BY id ASC LIMIT 1000;
SELECT * FROM posts WHERE id > 1000 ORDER BY id ASC LIMIT 1000;

ActiveRecord

Post.find_each { |post| post }

SQL that Rails 8.1.1 generates

SELECT "posts".* FROM "posts" ORDER BY "posts"."id" ASC LIMIT $1
SELECT "posts".* FROM "posts" WHERE "posts"."id" > $1 ORDER BY "posts"."id" ASC LIMIT $2

A cleaner alternative

Post.order(:title).find_each(cursor: [:title, :id], batch_size: 4) { |post| post }

Rails 8.1 accepts a cursor option to batch in a custom order. Include the primary key last so the order is unique.

Related form

SELECT * FROM posts ORDER BY id ASC LIMIT 4 OFFSET 0 -- then keyset on id
Post.in_batches(of: 4) { |relation| relation.update_all(published: true) }

What goes wrong

each loads everything

Post.all.each ran 1 query and built every object at once. On a table with millions of rows that exhausts memory.

find_each ignores your order

Post.order(:title).find_each ran ordered by id and logged: Scoped order is ignored, use :cursor with :order to configure custom order. Pass cursor to change it.

start, finish and order work

find_each(start: 3, finish: 5) yielded ids 3, 4 and 5. find_each(order: :desc) walked ids from 9 down to 1.

Use in_batches for bulk writes

in_batches yields a Relation per batch, so relation.update_all runs one UPDATE per batch instead of loading objects. Callbacks do not run.

find_each is a keyset scan, not OFFSET

Each batch uses WHERE id > last_id. That stays fast on deep pages, unlike OFFSET.

Convert your own find_each vs each query

Paste your SQL and press Convert. Always run .to_sql on the result and compare it with your original.

Questions

What is the difference between each and find_each?

each loads all rows with one query. find_each loads them in batches by primary key and yields one record at a time.

What is the default batch size for find_each?

1000 rows, according to the Rails API docs. Set batch_size to change it.

Can I sort in find_each?

Not with order alone, because Rails ignores it. Use the cursor option in Rails 8.1, with the primary key last.