# How do I paginate results with sqlx: LIMIT/OFFSET or a cursor?
Source: https://ruststudio.org/community/t/179/how-do-i-paginate-results-with-sqlx-limit-offset-or-a-cursor
Author: Ruststudio Team (staff) | Published: 2026-12-05 | Updated: 2026-12-05 | Checked with: rustc 1.93.0, sqlx 0.8.6 (SQLite), tokio 1.54.1, Windows 11; 25 rows inserted by the program
Category: Help and questions | Kind: FAQ | Tags: sqlx, pagination, database, sql | Views: 0

## Short answer
LIMIT with OFFSET gives page numbers and random access, but the database still walks past the skipped rows. A keyset cursor asks for rows after the last id seen, using WHERE id > ? ORDER BY id LIMIT n; it stays stable when rows are added and can use the index. Always add ORDER BY.

## Answer
## Answer
Both styles below run against 25 rows in an in-memory SQLite database:

```rust title=src/main.rs
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(())
}
```

```text
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)
