Answer#
Both styles below run against 25 rows in an in-memory SQLite database:
use sqlx::SqlitePool;
#[tokio::main]
async fn main() -> Result<(), sqlx::Error> {
let db = SqlitePool::connect("sqlite::memory:").await?;
sqlx::migrate!("./migrations").run(&db).await?;
for n in 1..=25 {
sqlx::query("INSERT INTO todos (title) VALUES (?)").bind(format!("todo {n}")).execute(&db).await?;
}
// Page number: simple, can jump to any page, but the database still walks past every skipped row.
let (page, per_page) = (3_i64, 10_i64);
let rows: Vec<(i64,)> = sqlx::query_as("SELECT id FROM todos ORDER BY id LIMIT ? OFFSET ?")
.bind(per_page).bind((page - 1) * per_page).fetch_all(&db).await?;
println!("page 3 (LIMIT/OFFSET): {:?}", rows.iter().map(|r| r.0).collect::<Vec<_>>());
// Keyset: "the rows after the last id I showed". Stable when rows are added, and it can use the index.
let mut after = 0_i64;
loop {
let rows: Vec<(i64,)> = sqlx::query_as("SELECT id FROM todos WHERE id > ? ORDER BY id LIMIT ?")
.bind(after).bind(10_i64).fetch_all(&db).await?;
let Some(last) = rows.last() else { break };
println!("after {after:>2}: {} rows, next cursor {}", rows.len(), last.0);
after = last.0;
}
Ok(())
}page 3 (LIMIT/OFFSET): [21, 22, 23, 24, 25]
after 0: 10 rows, next cursor 10
after 10: 10 rows, next cursor 20
after 20: 5 rows, next cursor 25| LIMIT / OFFSET | Keyset (cursor) | |
|---|---|---|
| Query | ORDER BY id LIMIT 10 OFFSET 20 | WHERE id > 20 ORDER BY id LIMIT 10 |
| Jump to page 7 | yes | no: you need the id of the row before it |
| Rows added while the user pages | rows can repeat or be skipped between pages | each page continues after the last row seen |
| Cost of a deep page | the database steps over every skipped row | uses the index to start at the cursor (when id is indexed) |
For an API, return the cursor with the page ("next": 20) and let the client send it back. No timings were measured for this thread; the cost column describes how the two queries work, so measure your own table if it matters.
Common mistakes#
- Paging without
ORDER BY. The database may return rows in any order, and pages can overlap. - Sorting by a column that is not unique (a date) and using it alone as the cursor. Rows with equal values can be skipped; add the id as a tie-breaker.
- Letting the client choose any page size. Cap it on the server.
Related questions#
How do I know the total number of pages?#
Run a separate SELECT count(*). It scans a lot of rows on big tables, so many APIs only report whether a next page exists.
Sources#
- sqlx documentation: https://docs.rs/sqlx/0.8.6/sqlx/ (read 2026-12-05)