How to paginate query results¶
This page splits a query's results into pages two ways: by page number with limit() and offset(), and by position with after() and before(). Use page numbers when users jump to page 7 of a small table; use positions for feeds, infinite scroll, APIs and large tables.
The examples page through seven articles, newest first. Declare the model, connect, and add the rows inside a session:
from datetime import date
from ferro import Field, Model, connect, engines
class Article(Model):
id: int | None = Field(default=None, primary_key=True)
title: str
published_on: date = Field(index=True)
await connect("sqlite::memory:", auto_migrate=True)
async with engines.session():
await Article.bulk_create(
[
Article(title="Choosing a primary key", published_on=date(2026, 1, 5)),
Article(title="Indexes that pay off", published_on=date(2026, 1, 12)),
Article(title="Reading a query plan", published_on=date(2026, 1, 12)),
Article(title="Keyset paging", published_on=date(2026, 1, 19)),
Article(title="Soft deletes", published_on=date(2026, 1, 26)),
Article(title="Storing UTC", published_on=date(2026, 2, 2)),
Article(title="Testing with SQLite", published_on=date(2026, 2, 9)),
]
)
from datetime import date
from typing import Annotated
from ferro import Field, Model, connect, engines
class Article(Model):
id: Annotated[int | None, Field(primary_key=True)] = None
title: str
published_on: Annotated[date, Field(index=True)]
await connect("sqlite::memory:", auto_migrate=True)
async with engines.session():
await Article.bulk_create(
[
Article(title="Choosing a primary key", published_on=date(2026, 1, 5)),
Article(title="Indexes that pay off", published_on=date(2026, 1, 12)),
Article(title="Reading a query plan", published_on=date(2026, 1, 12)),
Article(title="Keyset paging", published_on=date(2026, 1, 19)),
Article(title="Soft deletes", published_on=date(2026, 1, 26)),
Article(title="Storing UTC", published_on=date(2026, 2, 2)),
Article(title="Testing with SQLite", published_on=date(2026, 2, 9)),
]
)
published_on carries an index because both kinds of paging read the table in published_on order. The blocks below run inside this session; Sessions explains why every call needs one.
Pages by number with offset()¶
Order the rows, skip (page - 1) * per_page of them, and take per_page:
async def get_page(page: int, per_page: int) -> list[Article]:
return (
await Article.select()
.order_by(lambda article: article.published_on, "desc")
.order_by(lambda article: article.id, "desc")
.limit(per_page)
.offset((page - 1) * per_page)
.all()
)
Each call reads one page. Page 2, three to a page, holds the fourth to sixth newest articles:
page_two = await get_page(page=2, per_page=3)
assert [article.title for article in page_two] == [
"Keyset paging",
"Reading a query plan",
"Indexes that pay off",
]
Two articles share 12 January, so the second order_by() on id decides which comes first. Without it the database may return tied rows in either order, and a row can move from one page to the next between two requests.
Offset paging has two costs:
- Drift. A row added or deleted between two requests shifts every later page by one, so the reader sees a row twice or misses one.
- Deep pages are slow. The database reads and discards every skipped row, so
offset(100_000)reads 100,000 rows before it returns any.
Keyset (cursor) pagination¶
after() starts a page just after a row you already have. Build the ordered query once, read the first page, then pass its last row to after():
newest = (
Article.select()
.order_by(lambda article: article.published_on, "desc")
.order_by(lambda article: article.id, "desc")
.limit(3)
)
first_page = await newest.all()
assert [article.title for article in first_page] == [
"Testing with SQLite",
"Storing UTC",
"Soft deletes",
]
second_page = await newest.after(first_page[-1]).all()
assert [article.title for article in second_page] == [
"Keyset paging",
"Reading a query plan",
"Indexes that pay off",
]
The second page starts with "Keyset paging", the article after "Soft deletes". The database seeks straight to that position, so page 1,000 costs what page 2 costs, and rows added or deleted elsewhere do not shift the page.
before() goes the other way. Pass it the first row of a page to get the page before it, still newest first:
previous_page holds the same three articles as first_page. The order keys must include the primary key, so that every row has exactly one position; after() and before() raise ValueError when it is missing. Paging with after() and before() lists the other rules.
A paginated API endpoint¶
An API hands the client a cursor: a string that encodes the last row's position, which the client sends back for the next page. position_of() reads a row's position as a tuple of its order-key values, and after() accepts that tuple in place of the row:
NEWEST_FIRST = (
Article.select()
.order_by(lambda article: article.published_on, "desc")
.order_by(lambda article: article.id, "desc")
)
def encode_cursor(article: Article) -> str:
published_on, article_id = NEWEST_FIRST.position_of(article)
return f"{published_on.isoformat()}_{article_id}"
def decode_cursor(cursor: str) -> tuple[date, int]:
published_on, article_id = cursor.split("_")
return date.fromisoformat(published_on), int(article_id)
async def article_page(cursor: str | None = None, limit: int = 20) -> dict:
query = NEWEST_FIRST.limit(limit + 1)
if cursor is not None:
query = query.after(decode_cursor(cursor))
rows = await query.all()
items = rows[:limit]
return {
"items": items,
"next_cursor": encode_cursor(items[-1]) if len(rows) > limit else None,
}
article_page() asks for one row more than the page holds. If that row comes back, there is a next page and next_cursor points at the page's last row; if it does not, next_cursor is None, even when the last page is exactly full. Three calls walk all seven articles:
first = await article_page(limit=3)
assert first["next_cursor"] == "2026-01-26_5"
second = await article_page(cursor=first["next_cursor"], limit=3)
assert second["next_cursor"] == "2026-01-12_2"
last = await article_page(cursor=second["next_cursor"], limit=3)
assert [article.title for article in last["items"]] == [
"Choosing a primary key"
]
assert last["next_cursor"] is None
The third page holds the one remaining article, and its next_cursor is None.
A FastAPI endpoint opens a session for the request and returns article_page()'s result. Ferro models are Pydantic models, so FastAPI serializes the articles directly:
from fastapi import FastAPI, Query
from ferro import engines
from myapp.articles import article_page
app = FastAPI()
@app.get("/articles")
async def list_articles(
cursor: str | None = None,
limit: int = Query(20, ge=1, le=100),
):
async with engines.session():
return await article_page(cursor=cursor, limit=limit)
Clients call /articles, then /articles?cursor=<next_cursor> until next_cursor is null. le=100 caps the page size, so one request cannot ask for the whole table. A session per request shows other ways to open the session.
See also¶
- Paging with
after()andbefore(): the rules for positions,Noneorder keys and related columns. Query.after(),Query.before(),Query.limit()andQuery.offset()in the API reference.