Rails DISTINCT ON in ActiveRecord (PostgreSQL)
ActiveRecord has no DISTINCT ON method, so pass it to select as a string and add the matching order. The example returns the newest post for each user.
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 DISTINCT ON (user_id) * FROM posts
ORDER BY user_id, created_at DESC
ActiveRecord
Post.select("DISTINCT ON (user_id) *").order(:user_id, created_at: :desc)
SQL that Rails 8.1.1 generates
SELECT DISTINCT ON (user_id) * FROM "posts" ORDER BY "posts"."user_id" ASC, "posts"."created_at" DESC
What goes wrong
ORDER BY must start with the DISTINCT ON column
PostgreSQL requires order(:user_id, created_at: :desc). The first column picks the group, the rest pick the winner inside it. A missing or reordered column raises an error.
count raises a syntax error
Post.select("DISTINCT ON (user_id) *").count generates COUNT(DISTINCT ON ...) and PostgreSQL rejects it. Count a wrapped Relation: Post.from(relation, :posts).count.
PostgreSQL only
MySQL and SQLite have no DISTINCT ON. Use a window function with ROW_NUMBER() and filter on 1 when the code must be portable.
Convert your own DISTINCT ON 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 DISTINCT ON in Rails?
Call select("DISTINCT ON (user_id) *") and order by the same column first, for example .order(:user_id, created_at: :desc).
How do I get the latest record per group in ActiveRecord?
On PostgreSQL use DISTINCT ON. On other databases use a ROW_NUMBER() window function and keep rows where it equals 1.
Why does count fail with DISTINCT ON?
Rails wraps the select list in COUNT(...), which turns the expression into invalid SQL. Wrap the Relation with from and count that.
Related conversions
Rails Window Function in ActiveRecord
Convert SQL window functions like ROW_NUMBER OVER PARTITION BY to Rails ActiveRecord. Tested on Rails 8.1, including how to filter on the window result.
Rails GROUP BY HAVING in ActiveRecord
Convert SQL GROUP BY with HAVING to Rails ActiveRecord using group, having and count. Tested on Rails 8.1 with the generated SQL and the Hash it returns.
Rails CTE (WITH) in ActiveRecord
Convert a SQL WITH clause to Rails ActiveRecord using Relation#with and from. Tested on Rails 8.1 and PostgreSQL 16. Needs Rails 7.1.
All SQL converters
Every tested SQL to ActiveRecord conversion on this site.
Safe conversion guide
How to check that a converted query returns the same rows.