Querying on optional parameters Querying on optional parameters postgresql postgresql

Querying on optional parameters


You are right in that building a query string is a terrible idea. This problem is not a driver one. It is just SQL:

query = """    select *    from users    where        (%(age)s is null or %(age)s = age)        and        (%(name)s is null or %(name)s = name)"""parameters = dict(name = None, age = 35)cursor.execute(query, parameters)

If a certain parameter is passed as null it will not be filtered.