Cursor Pagination With SQLAlchemy

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

PythonData Fetching

Code

pythonsnippet
11 lines
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

Inside the snippet

The working surface is the function cursor_paginate — everything else is wiring.

Asynchronous boundaries use await, so failures surface as exceptions at the call site rather than being swallowed. select, asc, AsyncSession are the only symbols borrowed from sqlalchemy — the coupling is explicit and narrow.

What to watch for

  • External dependency: sqlalchemy — install it before running the snippet.

Where you would put it to use

Entry signature: def cursor_paginate(session, model, limit, after_id=None)

Callers only need cursor_paginate — everything else stays internal.

FAQ

Which packages must be installed first?
Yes. The imports resolve to `sqlalchemy`, which the package manager must provide.