Pagination
Page numbers or offset windows with totals, or keyset cursors for infinite lists.
page takes a page number, an offset window or an after cursor. Prefer
cursors: the cost of a page number grows with the offset, because Postgres reads and
discards every row before it, and a row inserted while someone pages shifts
the rest by one. Page numbers stay for tables where people jump to page 7
and the total matters.
Page numbers
const { items, page } = await db.customers
.page({ page: 2, size: 25, count: "exact", orderBy: { name: "asc" } })
.orThrow();
// page: { number: 2, size: 25, total: 81, pages: 4, hasMore: true }withCount: true is shorthand for count: "estimated": the total is exact up to 1,000 rows and the planner's estimate above it. Pass count: "exact" for an exact total, which scans every matching row. Without a count, total and
pages are null; with one, their type is number. hasMore comes from fetching
one extra row, so it never needs a count. Without orderBy, pages are
ordered by the primary key, so they never overlap.
An estimated or planned total says so: page.capped is true when total is the planner's estimate and false when it is exact. formatPageTotal(page, { locale?, capped? }) turns it into text, 12,300 for an exact total and ~12,300 for an estimate; pass capped: (n) => ... for your language's wording. db.customers.counted() is count() with the same flag: { count, capped }.
Offset and limit
When the caller already speaks in offsets (a data grid, a REST API with
offset and limit parameters), pass offset and limit instead of page
and size. The rows and the total come back in one request.
const { items, page } = await db.customers
.page({ offset: 40, limit: 20, count: "exact", orderBy: { name: "asc" } })
.orThrow();
// page: { number: 3, size: 20, total: 81, pages: 5, hasMore: true }The result has the same shape as a numbered page: size is the limit, and
number is the page the offset falls on (floor(offset / limit) + 1). An
offset past the last row returns no items and the total on both executors,
although PostgREST itself answers that read with a 416. Passing offset
together with page or size is an invalid_request error.
Cursors
const first = await db.customers
.page({ after: null, size: 25, orderBy: { name: "asc" } })
.orThrow();
const next = await db.customers
.page({ after: first.nextCursor, size: 25, orderBy: { name: "asc" } })
.orThrow();Cursors use keyset pagination: the next page is "rows after the last one", not an offset, so inserts do not shift pages and deep pages stay fast. The primary key is added as a tiebreaker, so rows with equal sort values are never skipped or repeated.
Nullable sort columns work too: the next page follows where Postgres puts
nulls (last for asc, first for desc, or what nulls says), so no row
with a null sort value is skipped. Give the order an index that matches it,
for example create index on customers (name, id), and each page is one
index range scan however deep it is.
Pass withCount: true to get total, the number of rows that match where
(the cursor is ignored). The first page reads it from the page request; each
later page sends one more request that only counts. Without withCount, a
cursor page has no total.
On the better-supabase/postgres executor the cursor compiles to a row
comparison, (name, id) > ($1, $2), when every column sorts the same way and
none is nullable.
A cursor is an opaque base64url string. Pass it back with the same orderBy
and where. The cursor records the table and the sort it continues, so a
cursor passed with another orderBy fails with an invalid_request error
instead of returning the wrong page; start the new order with after: null.
Lists and REST resources page by cursor with pagination: 'cursor' (see
list queries); their size stays capped
by maxPageSize.
Block lists and generated list functions
The list functions of the blocks that page by number (list_risks, list_meetings,
list_inspections, list_warranty_claims) and the function the list tag renders take after for
keyset paging and offset as an explicit option. Pass { paged: true } for { items, hasMore, nextCursor } and { total: true } for a total capped at totalCap (default 10,000), as
notification_page does. after and offset do not combine. See
Tags that render SQL.
Row caps
PostgREST returns at most db-max-rows rows for one read (1000 on hosted
projects, [api] max_rows in config.toml) and drops the rest without an
error. A list without limit can therefore look complete when it isn't.
export const betterSupabase = createSupabase(schema, { maxRows: 1000 });maxRowstells better-supabase the cap. It defaults to 1000; set it to what your project uses.- A read without
limitthat returnsmaxRowsrows asks for one more row. When that row exists, the read returns atruncatederror (HTTP 413) and the rows are not returned. Settruncation: "warn"to keep the rows, settruncated: trueon thequeryevent and log a warning once per table. - The fix is
limitfor a bounded list,pagefor everything else, or an aggregate when you only need a number.
Default order
list without orderBy orders by the primary key. Postgres has no
default row order, so without it two identical reads can return rows in a
different order after an update or a VACUUM, and limit picks arbitrary
rows. Pass orderBy to choose another order. Views and tables without a
primary key keep the database's order.
Sorting by a related row
orderBy takes a to-one relation with columns of the related table, one
level deep:
await db.invoices
.page({
page: 1,
size: 25,
orderBy: [{ organization: { name: "asc" } }, { number: "desc" }],
})
.orThrow();Over PostgREST this sends order=_bs1(name).asc with an empty embed of the
relation, or reuses the relation's include when you include it. The SQL
executor sorts by a scalar subquery. Rows without a related row sort as
null. To-many relations, cursor pages, aggregates, sorts inside an include
and SQLite return an error, since none of them can sort by a joined row.
Lint
The unbounded-read rule flags
list without limit on the tables gen marked as large in
supabase/snapshot.json, before they reach production.
Last updated on