I have an IF statement inside of db.execute, but I can't figure out how to run a normal command depending on the result. I want to run like apology inside of the db.execute for testing, but I can't figure out how to do anything with the results of the IF that isn't sql

ifbothexist = db.execute("SELECT :shares AND :user_id FROM portfolio", user_id=session["user_id"], shares = shares)

        if ifbothexist == True:
            return apology("True")
        elif ifbothexist == False:
            return apology("False")
        return apology("test")


This execute will always return a list whose length is the number of rows in portfolio.

Each dictionary in the list will contain one key/value pair.

The key will be '{s} AND {u}' where s is substituted with the value of (the python variable) shares and u is substituted with the value of session["user_id"]. You can view the sql that is executed in the flask log.

The (dict) value will be 0 if either shares or session["user_id"] is 0, otherwise it will be 1. (The boolean AND result of the two constants)

The if block will always return apology("test"). execute returns a list, so it is neither True nor False.

When you want to know if something exists in a table, it (generally) requires a WHERE clause.

When you want to know if any rows are returned from a query, you can test the length of the returned array, as with the python len function.

A simple example to determine (and display) whether user_id has any rows in portfolio.

userrows = db.execute("SELECT shares FROM portfolio WHERE user_id = :user_id", user_id=session["user_id"]))

        if len(userrows) > 0:
            return apology("True")
            return apology("False")


You cannot do anything with the results of the "IF" that isn't sql. You cannot do anything in a db.execute string that isn't sql. sqlite does not have an IF statement per se, it is part of an IF [NOT] EXISTS construct.

To change the program flow (i.e. call apology based on some condition), it needs to be done in python based on the result of execute like this example from login:

rows = db.execute("SELECT * FROM users WHERE username = :username",

# Ensure username exists and password is correct
if len(rows) != 1 or not check_password_hash(rows[0]["hash"], request.form.get("password")):
    return apology("invalid username and/or password", 403)
  • I added some code to the question. How would I do something like that? How do I compare whether or not both lines exist? I would like to do one thing if they both exist (which I thought would be if it equals true) and vice versa. Thanks!
    – Joel Banks
    May 31 '19 at 2:03
  • Answer emended to address posted code. May 31 '19 at 15:50

You must log in to answer this question.

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