Keyset pagination uses the last item's ID from the previous page to fetch the next set of rows, avoiding the performance issues of OFFSET on large datasets. Implement it by querying for records strictly greater than the last known cursor value and encoding that cursor in your API response.
func GetNextPage(db *sql.DB, lastID int64, limit int) ([]Item, error) {
var items []Item
rows, err := db.QueryContext(context.Background(), "SELECT id, name FROM items WHERE id > ? ORDER BY id ASC LIMIT ?", lastID, limit)
if err != nil { return nil, err }
defer rows.Close()
for rows.Next() {
var item Item
if err := rows.Scan(&item.ID, &item.Name); err != nil { return nil, err }
items = append(items, item)
}
return items, nil
}