Skip to main content

ActiveRecord Subquery in Rails

Pass a Relation to where and Rails builds IN (SELECT ...). Always call select on the inner Relation to name the column. Rails runs the whole thing as one query.

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 users
WHERE id IN (SELECT user_id FROM posts WHERE published = true)

ActiveRecord

User.where(id: Post.where(published: true).select(:user_id))

SQL that Rails 8.1.1 generates

SELECT "users".* FROM "users" WHERE "users"."id" IN (SELECT "posts"."user_id" FROM "posts" WHERE "posts"."published" = $1)

What goes wrong

Without select, Rails uses the primary key

User.where(id: Post.where(published: true)) compares users.id to posts.id, not posts.user_id. The query runs and returns wrong rows. Name the column with select(:user_id).

NOT IN returns nothing when the subquery has NULL

where.not(id: Post.select(:user_id)) generates NOT IN. If any posts.user_id is NULL, SQL evaluates the comparison as unknown and the result is empty. Add where.not(user_id: nil) to the inner Relation or use where.missing.

Prefer a Relation over a loaded array

where(id: Post.pluck(:user_id)) runs two queries and sends every id back to the database. Passing the Relation keeps it to one.

Convert your own subquery query

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

Questions

How do I write a subquery in ActiveRecord?

Pass a Relation as a where value and select the column, for example User.where(id: Post.where(published: true).select(:user_id)).

Does ActiveRecord run a subquery as one query?

Yes. Rails embeds the inner Relation as SQL, so the database runs a single statement.

Why does where.not with a subquery return no rows?

NOT IN with a NULL in the subquery result evaluates to unknown for every row. Filter NULLs out of the inner query.