Cursor Pagination With SQLAlchemy

Implement cursor-based pagination with SQLAlchemy for stable large dataset traversal.

PythonData Fetching

Code

snippet
from sqlalchemy import select, asc
from sqlalchemy.ext.asyncio import AsyncSession

async def cursor_paginate(session, model, limit, after_id=None):
    stmt = select(model).order_by(asc(model.id)).limit(limit + 1)
    if after_id:
        stmt = stmt.where(model.id > after_id)
    result = await session.execute(stmt)
    items = result.scalars().all()
    has_next = len(items) > limit
    return items[:limit], items[limit].id if has_next else None