How to check if query in SqlAlchemy returns empty result?

Question:

I’d like to perform a query like so:

    query = users.select().where(users.column.id == id)
    res = await database.execute(query)

I would then like to add some error handling by checking res. if not res does not seem to be correct. What is the proper way to do this?

Asked By: TheRealFakeNews

||

Answers:

You can try taking first object from your query and checking if it is Null like this

result = users.select().where(users.column.id == id).first()
if not result:
    print('query is empty')

The other way editing your code would be

res = query.first()

And then checking if it is Null

Answered By: Antonio Margaretti

Depending on the complexity of your query, it might be cheaper to wrap it inside a SELECT EXISTS(...) than to SELECT ... LIMIT 1, as Antonio describes. PostgreSQL probably knows to treat those queries the same, but according to this answer, not all DBMS might do so.

The beauty of such a solution is that it exists as soon as it finds any result — it does as little work as possible and is thus as cheap as possible. In SQLAlchemy that would be sa.select([sa.exists(query)])

Answered By: Ruben Helsloot
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.