Skip to main content

Rails includes vs preload vs eager_load

preload always runs a second query. eager_load always runs one query with a LEFT OUTER JOIN. includes picks one of those for you. It uses a JOIN only when your query references the association table.

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;
SELECT * FROM users WHERE id IN (1, 2, 3);

ActiveRecord

Post.preload(:user)

SQL that Rails 8.1.1 generates

SELECT X "users".* FROM "users" WHERE "users"."id" IN ($1, $2, $3)

A cleaner alternative

Post.eager_load(:user)

Pick eager_load when you filter or sort on the association table. Pick preload when you do not, because separate IN queries avoid wide JOIN rows.

Related form

SELECT posts.*, users.*
FROM posts
LEFT OUTER JOIN users ON users.id = posts.user_id
Post.eager_load(:user)

Related form

SELECT posts.*, users.*
FROM posts
LEFT OUTER JOIN users ON users.id = posts.user_id
WHERE users.name = 'u1'
Post.includes(:user).where(users: { name: "u1" })

What goes wrong

includes switches strategy

Post.includes(:user) ran 2 queries. Post.includes(:user).where(users: { name: "u1" }) ran 1 query with a JOIN. The hash condition names the users table, so Rails switched to eager_load.

String conditions need references

Post.includes(:user).where("users.name = 'u1'") failed with PG::UndefinedTable. Rails cannot see the table inside a string. Add .references(:users) or use eager_load.

preload cannot filter on the association

User.preload(:posts).where(posts: { published: true }) failed with PG::UndefinedTable: missing FROM-clause entry for table posts. preload never joins.

eager_load with limit runs two queries

User.eager_load(:posts).limit(2) first ran SELECT DISTINCT users.id with the JOIN, then loaded the rows. Rails does this so the limit counts users, not joined rows.

Convert your own includes vs preload vs eager_load 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 includes and preload?

preload always uses a separate query. includes uses a separate query unless your conditions reference the association table, then it uses a JOIN.

When should I use eager_load?

When you filter or order by a column on the association. eager_load forces one LEFT OUTER JOIN query.

Which one is fastest?

It depends on data shape. Measure with explain. A JOIN repeats parent columns on every child row, so wide parents with many children can favor preload.