Skip to main content

Rails WHERE IN Clause in ActiveRecord

Pass an Array to where. where(id: [1, 2, 3]) becomes IN (1, 2, 3), and where.not(id: [1, 2, 3]) becomes NOT IN. The same call accepts a Range and a Relation.

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 (1, 2, 3)

ActiveRecord

User.where(id: [1, 2, 3])

SQL that Rails 8.1.1 generates

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

Related form

SELECT * FROM users WHERE id NOT IN (1, 2, 3)
User.where.not(id: [1, 2, 3])

What goes wrong

An empty array becomes WHERE 1=0

where(id: []) returns no rows, so a missing filter never leaks every record. where.not(id: []) becomes 1=1 and returns all rows.

A nil in the array adds an IS NULL branch

where(id: [1, nil]) generates (id = 1 OR id IS NULL), which plain SQL IN never does. Call compact if you do not want the NULL match.

Very large arrays cost memory

Sending tens of thousands of ids is slow. Pass a Relation or join a temporary table, so the database reads the ids itself.

Convert your own IN clause 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 WHERE IN in Rails?

Use User.where(id: [1, 2, 3]). Rails generates WHERE users.id IN (1, 2, 3).

How do I write NOT IN in ActiveRecord?

Use User.where.not(id: [1, 2, 3]). Rails generates NOT IN.

What happens with an empty array in where?

Rails generates WHERE 1=0 and returns no rows.