Paginate and count rows
Read a large table page by page without missing rows, get the total for your page numbers, and pick the pagination that stays fast on the last page.
A read returns at most 1,000 rows. To go further, ask for one page at a time: by position (range(), offset()) or after the last row you read (after()). The total number of matching rows comes from count, exact or estimated.
Prerequisites#
-
A linked project:
aura link <project-id>. -
The example schema, installed with the service role key of the project:
export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docsIt creates
profiles,orgs,org_members,posts,todos, the viewopen_todosand the functiontodo_count(p_user uuid). See Example schema. -
AURABASE_URLin the environment, for the SDK andcurlexamples.
The examples create the table qd_page_events with 2,500 rows, read it with the service_role key, then remove it.
create table qd_page_events (
id bigint primary key,
label text not null
);
insert into qd_page_events select g, 'event ' || g from generate_series(1, 2500) g; ℹ No results (0 rows).The 1,000-row cap#
Every read returns 1,000 rows at most: it is the default when you set no limit, and the ceiling when you ask for more. The SDK tells you when rows were left out with meta.has_more:
import { createClient } from '@aurabase/aurabase-js'
const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)
const all = await admin.from('qd_page_events').select('id')
console.log('no limit:', all.data!.length, all.meta)
const more = await admin.from('qd_page_events').select('id').limit(5000)
console.log('limit 5000:', more.data!.length, more.meta)no limit: 1000 { has_more: true }
limit 5000: 1000 { has_more: true }has_more is computed by the SDK from the response; over REST, compare the number of rows to the total given by count (Pages over REST). The cap applies to reads of tables and views and to functions that return rows; it does not apply to SQL through aura db raw.
Offset pagination#
range(from, to) reads the rows at positions from to to, both included, counting from 0. Always sort on a unique column first, or the same row can appear on two pages:
import { createClient } from '@aurabase/aurabase-js'
const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)
const pageSize = 10
const page = 3
const { data, count, meta } = await admin
.from('qd_page_events')
.select('id, label', { count: 'exact' })
.order('id')
.range((page - 1) * pageSize, page * pageSize - 1)
console.log(data!.map((r) => r.id).join(','), count, meta?.has_more)
const same = await admin.from('qd_page_events').select('id').order('id').offset(20).limit(10)
console.log(same.data!.map((r) => r.id).join(','))21,22,23,24,25,26,27,28,29,30 2500 true
21,22,23,24,25,26,27,28,29,30range(20, 29) is offset(20).limit(10). On the last page, has_more is false. Each page costs more than the previous one: PostgreSQL still reads and skips the offset rows before the page.
Count rows#
count returns the number of rows that match the filters, whatever the range or the cap:
| Mode | How it is computed | Use it for |
|---|---|---|
'exact' | count(*) of the matching rows. | Totals you show to users, small and medium tables. |
'planned' | The row estimate of PostgreSQL's query planner. | Very large tables where a rough total is enough. |
'estimated' | exact for small results, planned above a threshold (measured: the exact 500 for 500 rows, the planner's 1200 for 1,500 rows). | Same as planned, with an exact value on small results. |
import { createClient } from '@aurabase/aurabase-js'
const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)
const total = await admin.from('qd_page_events').select('*', { count: 'exact', head: true })
console.log('rows:', total.count, 'data:', total.data)
const filtered = await admin.from('qd_page_events').select('id', { count: 'exact', head: true }).like('label', 'event 1%')
console.log('matching "event 1%":', filtered.count)
const withRows = await admin.from('qd_page_events').select('id').gt('id', 2495).count()
console.log('count() method:', withRows.count, withRows.data!.map((r) => r.id).join(','))
const planned = await admin.from('qd_page_events').select('id', { count: 'planned', head: true })
console.log('planned is a number:', typeof planned.count === 'number')rows: 2500 data: null
matching "event 1%": 1111
count() method: 5 2496,2497,2498,2499,2500
planned is a number: truehead: truesends aHEADrequest: you getcountand no rows..count()(or.count('planned')) is the same as thecountoption ofselect().plannedandestimatedcome from table statistics, which can be far from the truth on a table that was just loaded (measured:1200for 1,500 fresh rows). Useexactwhen the number matters.- A count is lost on inserts and updates for now:
insert(…).select().count('exact')returnscount: null. Count with a separate read.
Pages over REST#
Over REST, limit and offset go in the query string and count=exact adds the total. The response carries a Content-Range header, <first>-<last>/<total>, and the status 206 Partial Content when the page is not the whole result:
body=$(mktemp)
curl -s -D - -o "$body" \
"$AURABASE_URL/v1/db/qd_page_events?select=id&order=id&limit=3&offset=10&count=exact" \
-H "apikey: $AURABASE_SERVICE_ROLE_KEY" | grep -iE '^(HTTP|content-range)'
cat "$body"
echo
rm -f "$body"HTTP/1.1 206 Partial Content
content-range: 10-12/2500
{"data":[{"id":11},
{"id":12},
{"id":13}],"meta":{"total":2500}}The total is also in meta.total. Without count, the header ends with /* (total unknown). Content-Range is exposed to browser code by CORS.
Keyset pagination#
Keyset pagination asks for the rows after the last one you read: after(column, lastValue) sorts on the column and adds column > lastValue. Each page costs the same, and rows inserted meanwhile never shift a page:
import { createClient } from '@aurabase/aurabase-js'
const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)
let last: number | undefined
let pages = 0
let rows = 0
for (;;) {
const q = admin.from('qd_page_events').select('id, label').limit(1000)
const { data, error } = await (last === undefined ? q.order('id') : q.after('id', last))
if (error) throw error
if (!data.length) break
pages += 1
rows += data.length
last = data[data.length - 1].id
}
console.log({ pages, rows, last })
console.log(admin.from('qd_page_events').select('id').after('id', 1000).limit(3).buildQueryString())
const cursor = await admin.from('qd_page_events').select('id').cursor('abc')
console.log('cursor():', cursor.error?.status, cursor.error?.code){ pages: 3, rows: 2500, last: 2500 }
select=id&id=gt.1000&order=id.asc&limit=3
cursor(): 400 BAD_REQUESTThe column must be unique and sorted (a primary key, or created_at plus id for a feed). after(column, value, { ascending: false }) walks backwards with lt. Over REST, it is ?order=id.asc&id=gt.1000&limit=1000. cursor() of the SDK is for MongoDB projects only; on PostgreSQL it is refused with a message that points to after().
Pages in SQL#
From a server, the same pages are limit and offset, or a where on the last value read, with aura db raw or db.sql(). SQL through this endpoint is not capped at 1,000 rows, so always write the limit:
aura db raw "select id, label from qd_page_events order by id limit 3 offset 20"
aura db raw "select id, label from qd_page_events where id > 1000 order by id limit 3"
aura db raw "select count(*) as total from qd_page_events" id │ label
─────┼─────────
21 │ event 21
22 │ event 22
23 │ event 23
ℹ 3 row(s).
id │ label
─────┼───────────
1001 │ event 1001
1002 │ event 1002
1003 │ event 1003
ℹ 3 row(s).
total
─────
2500
ℹ 1 row(s).Choose a pagination#
| Need | Use | Why |
|---|---|---|
| Page numbers in a table view | range() with count: 'exact' | Jump to any page and show "page 3 of 250". |
| Infinite scroll, feeds, exports | after() | Constant cost, no duplicate or missing rows when data changes. |
| Read a whole table in a script | after() in a loop | Every row exactly once, 1,000 at a time. |
| A total for a very large table | count: 'planned' | No full scan; the value is approximate. |
Result#
aura db raw "select count(*) as rows, min(id) as first, max(id) as last from qd_page_events" first │ last │ rows
──────┼──────┼─────
1 │ 2500 │ 2500
ℹ 1 row(s).Common errors#
| Message | Cause | Fix |
|---|---|---|
data.length is 1,000 and meta.has_more is true | The 1,000-row cap. | Read the next page with range() or after(). |
416 POSTGREST_ERROR Requested range not satisfiable | range() or offset beyond the last row, with count. | Stop when a page is shorter than the page size, or compare to count. |
400 BAD_REQUEST Invalid request: Cursor pagination … is not available on PostgreSQL projects (it is MongoDB-only) | cursor() on a PostgreSQL project. | Use after() or range(). |
count is null after an insert or update | The count of a write is lost by the gateway today. | Count with a separate select(…, { count: 'exact', head: true }). |
| The same row on two pages | Offset pagination without order(), or on a column that is not unique. | Sort on a unique column, or add id as a second sort key. |
Clean up#
aura db raw "drop table qd_page_events" ℹ No results (0 rows).