Skip to main content

Rails Window Functions: ROW_NUMBER in ActiveRecord

Latest row per group, top N and running totals, with the SQL Rails really generates

R
Raza Hussain
· 7 min read · 25
Two stacked stone blocks carry the ROW_NUMBER subquery code, with the where(rn: 1) line highlighted in red, showing rank first then filter.

ActiveRecord has no window function API. Write the OVER (...) part as a string inside select, then wrap that relation in from so you can filter on the window result. This is the pattern for “latest row per group” and “top N per group”. Rails will not let you put WHERE rn = 1 on the same query, because SQL does not allow it either.

Every example below ran on ActiveRecord 8.1.1 with PostgreSQL 16.15 on 26 November 2026. The SQL shown is the SQL Rails produced.

The schema used in every example

class Order < ApplicationRecord; end
# orders: id, customer_id (integer), total_cents (integer), created_at (datetime)

Six rows. Customer 1 has three orders (5000, 7500 and 7500 cents, one per day). Customer 2 has two (1200 and 9900). Customer 3 has one (300).

Latest order per customer with ROW_NUMBER

SQL:

SELECT * FROM (
  SELECT orders.*,
         ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_at DESC, id DESC) AS rn
  FROM orders
) orders
WHERE rn = 1
ORDER BY customer_id

ActiveRecord:

ranked = Order.select(
  "orders.*, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_at DESC, id DESC) AS rn"
)

Order.from(ranked, :orders).where(rn: 1).order(:customer_id).map { |o| [o.id, o.customer_id, o.rn] }
# => [[3, 1, 1], [5, 2, 1], [6, 3, 1]]

Generated SQL:

SELECT "orders".* FROM (
  SELECT orders.*, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_at DESC, id DESC) AS rn
  FROM "orders"
) orders WHERE "orders"."rn" = 1 ORDER BY "orders"."customer_id" ASC

from(ranked, :orders) gives the subquery the alias orders, so the rest of your Rails code (hash where, order(:customer_id)) keeps working. The extra rn column becomes an attribute on each record.

Note the id DESC tie-breaker. Without it, two orders with the same created_at can swap places between runs.

Why WHERE rn = 1 fails on the same query

ranked.where("rn = 1").to_a
# ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:  column "rn" does not exist

SQL evaluates WHERE before window functions run, so the alias does not exist yet. The subquery wrapper above is the fix. HAVING does not help either, since rn is not an aggregate.

Top N per group

Change the filter. The rest stays the same:

Order.from(ranked, :orders).where("rn <= ?", 2).order(:customer_id, :rn)
      .map { |o| [o.id, o.customer_id, o.rn] }
# => [[3, 1, 1], [2, 1, 2], [5, 2, 1], [4, 2, 2], [6, 3, 1]]

Two newest orders for each customer. Customer 3 has one order, so it returns one.

ROW_NUMBER, RANK and DENSE_RANK with ties

Customer 1 has two orders worth 7500 cents. This is how the three functions treat the tie:

Order.where(customer_id: 1)
     .select("id, total_cents,
              ROW_NUMBER() OVER (ORDER BY total_cents DESC, id) AS rn,
              RANK()       OVER (ORDER BY total_cents DESC)     AS rnk,
              DENSE_RANK() OVER (ORDER BY total_cents DESC)     AS drnk")
     .order("total_cents DESC", :id)
     .map { |o| [o.id, o.total_cents, o.rn, o.rnk, o.drnk] }
# => [[2, 7500, 1, 1, 1], [3, 7500, 2, 1, 1], [1, 5000, 3, 3, 2]]
Function Tie behaviour Result for 7500, 7500, 5000
ROW_NUMBER Always unique, ties broken by your ORDER BY 1, 2, 3
RANK Ties share a rank, then a gap 1, 1, 3
DENSE_RANK Ties share a rank, no gap 1, 1, 2

Use ROW_NUMBER when you need exactly one row per group. Use RANK or DENSE_RANK when ties should all be kept (“everyone with the top score”).

Running total with SUM OVER

running = Order.select(
  "orders.*, SUM(total_cents) OVER (PARTITION BY customer_id ORDER BY created_at, id) AS running_cents"
).order(:customer_id, :created_at, :id)

running.map { |o| [o.id, o.customer_id, o.running_cents] }
# => [[1, 1, 5000], [2, 1, 12500], [3, 1, 20000], [4, 2, 1200], [5, 2, 11100], [6, 3, 300]]

Keep a unique column in the window ORDER BY. When ORDER BY is present, PostgreSQL’s default frame includes all rows with the same sort value. I tested a table with two rows on the same day (values 10 and 20). SUM(v) OVER (ORDER BY d) returned 30 for both rows. SUM(v) OVER (ORDER BY d, id) returned 10 and 30.

Compare to the previous row with LAG

Order.where(customer_id: 1)
     .select("id, total_cents,
              LAG(total_cents) OVER (ORDER BY created_at, id) AS prev_cents,
              total_cents - LAG(total_cents) OVER (ORDER BY created_at, id) AS delta")
     .order(:created_at, :id)
     .map { |o| [o.id, o.prev_cents, o.delta] }
# => [[1, nil, nil], [2, 5000, 2500], [3, 7500, 0]]

The first row has no previous row, so LAG returns NULL and Rails gives you nil.

Pitfalls I hit

count breaks on a window select. running.count raised PG::SyntaxError: syntax error at or near "AS", because Rails put your select list inside COUNT(...). Use running.except(:select, :order).count, or wrap it: Order.from(running, :orders).count. Both returned 6.

Plain strings in order work for bare names like order("rn"). Expressions need Arel.sql.

Subquery join as an alternative

If you need to keep the outer query as a normal Order relation (for includes, scopes or update_all targets), join the ranked ids instead:

ranked_ids = "(SELECT id, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_at DESC, id DESC) AS rn FROM orders) ranked"

Order.joins("INNER JOIN #{ranked_ids} ON ranked.id = orders.id")
     .where("ranked.rn = 1")
     .order(:customer_id)
     .pluck(:id)
# => [3, 5, 6]

Or filter with Order.where(id: Order.from(ranked, :orders).where(rn: 1).select(:id)), which also returned [3, 5, 6].

Which form to use

Need Use
One latest row per group, PostgreSQL only DISTINCT ON, see the post linked below
One row per group, any database with window functions ROW_NUMBER + from
Top N per group ROW_NUMBER + where("rn <= ?", n)
Ties kept RANK or DENSE_RANK
Running totals, previous row SUM OVER, LAG in select

Window functions exist in PostgreSQL, MySQL 8.0 and later, and SQLite 3.25 and later. If you are on an older MySQL, this pattern will not run.

Always read .to_sql before shipping. For a large table, add an index that matches PARTITION BY plus the window ORDER BY (here customer_id, created_at) and check the plan with EXPLAIN. This post on reading generated SQL shows how. For PostgreSQL’s shorter option see SQL SELECT DISTINCT in Rails ActiveRecord: distinct, DISTINCT ON and the ORDER BY error. For conditional columns inside the select list see SQL CASE WHEN in Rails ActiveRecord.

Have a window function query to translate? Paste it into the SQL to ActiveRecord converter and compare the result with .to_sql in your console.

Frequently asked questions

Can I use WHERE on a window function alias in ActiveRecord?
No. SQL runs WHERE before window functions, so Rails raises PG::UndefinedColumn. Wrap the ranked relation with from and filter the outer query.
What is the difference between ROW_NUMBER, RANK and DENSE_RANK?
ROW_NUMBER is always unique. RANK gives ties the same number and skips the next ones. DENSE_RANK gives ties the same number without gaps.
Why does count fail on a relation with a window function in select?
Rails wraps the select list inside COUNT and the result is invalid SQL. Use except(:select, :order).count or count the relation wrapped with from.
Does ActiveRecord have built-in window function methods?
Not in 8.1.1. You pass the OVER clause as a string to select.
Which databases support window functions?
PostgreSQL, MySQL 8.0 and later, and SQLite 3.25 and later.

Was this article helpful?

Your feedback helps us improve our content

Be the first to vote!

How We Verify Conversions

Every conversion shown on this site follows a strict verification process to ensure correctness:

  • Compare results on same dataset — We run both SQL and ActiveRecord against identical test data and verify results match
  • Check generated SQL with to_sql — We inspect the actual SQL Rails generates to catch semantic differences (INNER vs LEFT JOIN, WHERE vs ON, etc.)
  • Add regression tests for tricky cases — Edge cases like NOT EXISTS, anti-joins, and predicate placement are tested with multiple scenarios
  • Tested on Rails 8.1.1 — All conversions verified on current Rails version to ensure compatibility

Last updated: November 26, 2026

Try These Queries in Our Converter

See the SQL examples from this article converted to ActiveRecord—and compare the SQL Rails actually generates.

25

Leave a Response

Responses (0)

No responses yet

Be the first to share your thoughts

R

Raza Hussain

Full-stack developer specializing in Ruby on Rails, React, and modern JavaScript. 15+ years upgrading and maintaining production Rails apps. Led Rails 4/5 → 7 upgrades with 40% performance gains, migrated apps from Heroku to Render cutting costs by 35%, and built systems for StatusGator, CryptoZombies, and others. Available for Rails upgrades, performance work, and cloud migrations.

💼 15 years experience 📝 58 posts