2

This probably isn't a new question but I have not been able to find a decent solution after googling and digging through SO for a while. I want to have a conditional AND added to my WHERE clause based on if a variable is set or not.

I could put in a ternary into the string format but that does not seem like a good solution.

def run_query(start_date, end_date, value):
    query = """
    SELECT * FROM table WHERE value = %(value)s {date_clause}""".format(date_clause = "AND start_date >= %(start_date)s AND end_date <= %(end_date)s" if start_date is not None and end_date is not Null else "")

cursor.execute(query, {"start_date": None, "end_date": None, "value": value})

1 Answer 1

1

You can use the Postgres function COALESCE()

query = """
SELECT * 
FROM my_table 
WHERE column = %(value)s 
AND otherColumn = COALESCE(%(otherValue)s, '')

"""

When otherValue is None then will be converted to Postgres NULL and COALESCE() return an empty string.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks forgot about COALESCE I don't think that would work if my conditional check is dates though, not sure if an empty string would work. Edited my post to show what I ended up doing. I am looking into pyscopg2 sql.SQL composition as well initd.org/psycopg/docs/sql.html#module-psycopg2.sql
Be aware that this can be extremely slow when you have more data: stackoverflow.com/questions/6426436/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.