0

I posted my code in another post I have made a lot of revisions. Kind of irrelevant but just thought I should mention it if someone goes through my last post.

I have a select statement. Lets say my select statement returns empty because my database is empty under certain conditions. Can a select return nothing without causing an error? Also How do I create a if condition that returns True if the database is empty?

1 Answer 1

0

It won't return "nothing" (None in Python), but it can return an empty result list. Like a

SELECT * FROM users WHERE 0=1;

The condition is always false, so it would return no rows, and with our API, this would result in an empty list (same as [] or list()). An empty list in Python is falsy (bool([]) returns False), so you can do either if len(result): or if result: to check whether the list has elements.

A test for an empty table could be like

rec_count = db.execute("SELECT COUNT(*) AS cnt FROM my_table;")[0]["cnt"]

if not rec_count:
    # table empty

but you could also have the database return something for all records and do a len(result) on the returned list. I simply prefer to return as little as possible.

1
  • Just want to double check. Then my question is answered if I am correct. 'empty_list = db.execute ('SELECT * FROM users WHERE 0=1')' Will this return true every time? 'if len(empty_list) == 0 return True:'
    – grggthwrth
    Commented May 26, 2019 at 4:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .