With Pagy 43, what SQL does pagy(:offset, scope) run per page, and what do the :countish and :countless paginators change about it?
answer
- two queries versus one
- COUNT memoized in the page param
- ttl: triggers a recount
- limit + 1 rows, count nil
- headless: true skips the helpers
basics
~20 s:offset runs a COUNT plus an OFFSET/LIMIT select on every page. :countish counts once, or again after an optional ttl:, and carries the total in its page links. :countless never counts: it fetches limit + 1 rows to learn whether a next page exists.
solid answer
~40 s`pagy(:offset, scope)` runs `SELECT COUNT(*)` and then `LIMIT 20 OFFSET n` on every request, and returns a lazy relation. `:countish` (added in Pagy 43.2) runs the `COUNT` only on the first request and writes the total into every page link, so later pages run just the select; `ttl: 300` recounts once the memoized value is older than 300 seconds. `:countless` never counts: it selects `limit + 1` rows, uses the extra row to know whether a next page exists, and returns an eager `Array`. Its `count` is `nil`, so `last` is only the highest page known so far, `info_tag` says "Page 3 of 4", and `headers_hash` drops the totals. For an admin product list I'd use `:countish`; for an append-only log nobody pages to the end, `:countless`.
code
ruby · 5 lines# Admin product list: count once, recount after five minutes
@pagy, @products = pagy(:countish, Product.order(:name), ttl: 300)
# Audit log, newest first: never count
@pagy, @events = pagy(:countless, AuditEvent.order(id: :desc))go deeper
Remember that :offset counts on every page, :countish counts once and :countless never counts.
Explain the limit + 1 trick, where :countish keeps its memoized total, why :countless returns an Array, and what info_tag and headers_hash lose without a count.
Choose per screen from table size and how much the UI needs the total, weigh a stale count against COUNT load, and know when deep OFFSET itself is the bottleneck.
Set a house rule for which lists may show exact totals, and how fresh they must be, measured against database load.
## Three offset paginators, one difference All three paginators below use **offset pagination**: page *n* starts after `limit * (n - 1)` rows and is read with SQL `OFFSET` and `LIMIT`. They differ only in how they learn the **total**, which the nav needs to show the last page and the info line needs for "of 324 in total". On a large table that `COUNT(*)` can cost as much as the page query itself. ## `:offset`: count on every request ```ruby @pagy, @products = pagy(:offset, Product.order(:name)) ``` On every request Pagy: 1. runs `collection.count(:all)`, a `SELECT COUNT(*) FROM "products"`; 2. computes `last = ceil(count / limit)` and the offset; 3. returns `collection.offset(40).limit(20)`, a **lazy relation** that runs when iterated. For a relation with `group`, `count` returns a Hash and Pagy takes its size; `count_over: true` asks for `COUNT(*) OVER ()` instead. Every helper works, because the total is exact. ## `:countish`: count once, carry it in the URL `:countish` (added in **Pagy 43.2.0**) is `:offset` with a **memoized count**. The first request counts. Every link the helpers render then carries the total inside the page param, so `page=3+324` is page 3 with a count of 324. Later requests read the count back from the param and skip the `COUNT` query. - With no `ttl:` it counts **once** and reuses that number for the whole browsing session. - `ttl: 300` stores an epoch beside the count and **recounts** when it is older than 300 seconds. - All helpers work, but the total can be **stale** while rows are inserted or deleted, and the count is whatever the link carried. ## `:countless`: never count ```ruby @pagy, @events = pagy(:countless, AuditEvent.order(id: :desc)) ``` `:countless` runs **one query per page**: `LIMIT 21 OFFSET 40` for a limit of 20. If 21 rows come back there is a next page; Pagy drops the extra row and returns an **eager `Array`** of 20. | | `:offset` | `:countish` | `:countless` | |---|---|---|---| | queries per page | COUNT + select | select (COUNT on first or after `ttl`) | select of `limit + 1` | | `count` | exact | memoized | `nil` | | `last` | real last page | real (memoized) | highest page known so far | | `@records` | lazy relation | lazy relation | eager `Array` | | `info_tag` | "Displaying items 41-60 of 324 in total" | same | "Page 3 of 4" | The costs of `:countless`: - the nav cannot link beyond the highest page known; Pagy 43 remembers it in the page param (`page=2+5`), so stepping back still shows forward links; - `headers_hash` omits `total-count`, `total-pages` and the `rel="last"` link; - `headless: true` skips the eager load and the bookkeeping entirely, for infinite scroll or an API. The helpers no longer work then, and the client stops when a page returns fewer rows than `limit`. ## Choosing - A product list of a few thousand rows: `:offset`, which is simple and exact. - The same list grown large, where admins still want "page 17 of 900": `:countish` with a `ttl:` that matches how fresh the total must be. - A million-row audit log, newest first, where nobody jumps to the last page: `:countless`. If deep pages also get slow because the database must still walk past every skipped row, `:keyset` is the next step. ## Reading the result in code The object answers the same readers in all three cases, but with different certainty: - `@pagy.count` is exact on `:offset`, possibly stale on `:countish`, and `nil` on `:countless`; - `@pagy.last` is the real last page on the first two and the highest page seen so far on `:countless`; - `@pagy.next` is `nil` on the final page everywhere, which is all an "older events" button needs. Code that branches on `@pagy.count` therefore has to handle `nil` before it switches a list to `:countless`. The same goes for a view that prints a total or a JSON response that promises one. None of the three fixes offset's **data shift**, where rows inserted while someone browses move other rows across page boundaries. Recounting on `:countish` does not fix it either.
- With Pagy 43, why does @events from pagy(:countless, ...) behave differently from @products from pagy(:offset, ...)?`:offset` returns `collection.offset(...).limit(...)`, a lazy relation you can still chain or `includes`. `:countless` must load the page to count the `limit + 1` rows, so it returns an already-loaded `Array` of `limit` records; chaining relation methods onto it fails. With `headless: true` it skips that load and returns the relation, but the helpers stop working.
- On a grouped relation such as Order.group(:customer_id), how does Pagy 43's :offset count it?`count(:all)` on a grouped relation returns a Hash of group to count, and Pagy uses the Hash's size, which loads one row per group. Passing `count_over: true` makes Pagy run `COUNT(*) OVER ()` and pick a single value instead, which suits large grouped results.
- Believes :countless still runs COUNT but caches it in Rails.cache.
- Says :countish recounts on every page unless ttl: is set.
- Calls .where or .includes on the Array that :countless returns.
- Thinks recounting with ttl: fixes rows shifting between offset pages.
- Expects headers_hash on a :countless page to include total-count.
Assumes Pagy 43.7 on Rails 8.1; :countish arrived in Pagy 43.2.0, and Pagy 43 made :countless remember the last known page in the page param.