Skip to main content

Rails WHERE EXISTS in ActiveRecord

Build the inner query as a Relation and wrap it in arel.exists. The example returns users who have at least one post. Rails 8.1 emits SELECT "posts".* inside EXISTS, which PostgreSQL treats the same as SELECT 1.

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 EXISTS (SELECT 1 FROM posts WHERE posts.user_id = users.id)

ActiveRecord

User.where(Post.where("posts.user_id = users.id").arel.exists)

SQL that Rails 8.1.1 generates

SELECT "users".* FROM "users" WHERE EXISTS (SELECT "posts".* FROM "posts" WHERE (posts.user_id = users.id))

A cleaner alternative

User.where("EXISTS (SELECT 1 FROM posts WHERE posts.user_id = users.id)")

A plain SQL string is also fine here. It has no user input, and it keeps SELECT 1 exactly as you wrote it.

What goes wrong

joins duplicates rows, EXISTS does not

User.joins(:posts) returns a user once per post. EXISTS returns each user once and stops at the first match, so it is the safer choice for a has-many relation.

where.associated is an INNER JOIN

User.where.associated(:posts) generates INNER JOIN with posts.id IS NOT NULL. It reads well but still repeats users with many posts. Add distinct, or use EXISTS.

Index the foreign key

EXISTS runs the inner query for each candidate user. An index on posts.user_id keeps that cheap.

Convert your own EXISTS 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 EXISTS in ActiveRecord?

Use User.where(Post.where("posts.user_id = users.id").arel.exists). Rails adds WHERE EXISTS (subquery) to the SQL.

Is EXISTS faster than joins?

For has-many checks it avoids duplicate rows and stops at the first match. Measure with explain on your own data, because the planner may rewrite either form.

How do I check that a record exists in Rails?

Call exists? on a Relation, for example Post.where(user_id: 1).exists?. It runs SELECT 1 ... LIMIT 1.