Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

1.1K
Views
How to check if query in SqlAlchemy returns empty result?

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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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

over 4 years ago · Santiago Trujillo Report

0

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)])

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!