Skip to main content

Rails GROUP BY HAVING in ActiveRecord

Chain group, having and count. The example finds users with more than five posts. The result is a Hash of user_id to count, not a Relation of Post records.

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 user_id, COUNT(*) FROM posts
GROUP BY user_id
HAVING COUNT(*) > 5

ActiveRecord

Post.group(:user_id).having("COUNT(*) > ?", 5).count

SQL that Rails 8.1.1 generates

SELECT COUNT(*) AS "count_all", "posts"."user_id" AS "posts_user_id" FROM "posts" GROUP BY "posts"."user_id" HAVING (COUNT(*) > $1)

What goes wrong

The result is a Hash

Post.group(:user_id).having(...).count returns something like {1 => 8}. You cannot chain where or order on it. Build the grouped Relation first, and call count last.

Pass HAVING values as placeholders

having("COUNT(*) > ?", 5) binds the value. Interpolating a variable into the string opens the query to SQL injection.

HAVING filters groups, WHERE filters rows

A condition on a plain column belongs in where, which runs before grouping and can use an index. Keep only aggregate conditions such as COUNT(*) in having.

Convert your own GROUP BY HAVING query

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

Questions

How do I use HAVING in Rails?

Call having after group, for example Post.group(:user_id).having("COUNT(*) > ?", 5).count. Rails adds HAVING (COUNT(*) > 5) to the query.

What does group.count return in ActiveRecord?

A Hash that maps each group value to its count, for example {1 => 8}. It is not a Relation.

Can I use where and having together?

Yes. where filters rows before grouping and having filters the groups after. Put non-aggregate conditions in where for speed.