Skip to main content

Rails Window Function in ActiveRecord

ActiveRecord has no window function API. Add the expression to select as a string with an alias. The example numbers each user's posts from newest to oldest.

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 id, user_id,
  ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC) AS rn
FROM posts

ActiveRecord

Post.select(:id, :user_id, "ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC) AS rn")

SQL that Rails 8.1.1 generates

SELECT "posts"."id", "posts"."user_id", ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC) AS rn FROM "posts"

What goes wrong

You cannot filter on the window alias in WHERE

SQL evaluates WHERE before window functions. To keep rn = 1, wrap the Relation: Post.from(relation, :posts).where("rn = 1"). That form ran on PostgreSQL 16 here.

count raises a syntax error

Calling count on the select with the window expression fails, because Rails wraps the whole expression in COUNT(...). Count the wrapped Relation instead.

The alias is available on each record

record.rn returns the value. It is not a model column, so it is lost when you reload.

Convert your own window function 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 ROW_NUMBER in ActiveRecord?

Pass the expression to select with an alias: Post.select(:id, "ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC) AS rn").

How do I filter on a window function result in Rails?

Wrap the Relation with from and add where on the alias, for example Post.from(relation, :posts).where("rn = 1").

Does Rails have a window function method?

No. Use a raw select string, or build the expression with Arel.