[Answered ]-Fastest way to find out whether row or one of set of rows exists in database accesed via SqlAlchemy

1👍

You could do something like this:

async with async_session() as session:
    stmt = select(User.id).where(User.id.in_([4, 5])).limit(1)
    result = await session.scalars(stmt)
    item = result.first()

item will be an int (truthy) if at least one row exists, otherwise it will be None (falsy). If you want a true boolean value you could always do

    row_exists = bool(result.first())

instead.

A more complete example of ORM with async can be found in the SQLAlchemy documentation here.

Leave a comment