I'm working with postgres in python and I want to write a clear query that optionally allows WHERE clause subsetting, but doesn't require me writing an exponential explosion of whether the subsetting where clauses exist or not. Specifically, I have the following:
query = """
select * -- in reality, something more complicated
from myTable t
WHERE
t.first_id in :args1 AND
t.second_id in :args2
"""
I would like to duplicate as little as possible, and for this query to return sensibly:
When args1 is null, and args2 is null
When args1 is null, and args2 has 1 argument
When args1 is null, and args2 has n arguments
When args1 has 1 argument, and args2 is null
When args1 has 1 argument, and args2 has 1 argument
When args1 has 1 argument, and args2 has n arguments
When args1 has n arguments, and args2 is null
When args1 has n arguments, and args2 has 1 argument
When args1 has n arguments, and args2 has n arguments
Where args1 can be:
args1 = []
args1 = ["a"]
args1 = ["a", "b"]
...for example, and similar for args2.
As you can see above,
(1) is effectively no WHERE clause
(2) is effectively remove the first argument and the AND
(2) Would also likely want an equality operator = 'a', rather than an in ('a')
...etc.
For 2 clauses and 3 options, we have 3^2 = 9 different queries to write. If we add another 1-2 where clauses, this quickly becomes overwhelming and duplicates a lot of code for what is effectively the same problem. While I can write each of these queries out and switch case on them, I suspect this is a syntax SQL can do for me, and that has possibly been answered a thousand times on stackoverflow but I can't seem to find.
I'm using sqlalchemy in python if that changes anything.