FAQ - Help and questions

How do I paginate results with sqlx: LIMIT/OFFSET or a cursor?

#sqlx#pagination#database#sqlpublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

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.

Checked with rustc 1.93.0, sqlx 0.8.6 (SQLite), tokio 1.54.1, Windows 11; 25 rows inserted by the program

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

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

src/main.rsrust
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 / OFFSETKeyset (cursor)
QueryORDER BY id LIMIT 10 OFFSET 20WHERE id > 20 ORDER BY id LIMIT 10
Jump to page 7yesno: you need the id of the row before it
Rows added while the user pagesrows can repeat or be skipped between pageseach page continues after the last row seen
Cost of a deep pagethe database steps over every skipped rowuses 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.

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet