3 ms·
select * from foo where case when :filter_on_a and not :filter_on_b then a=:a when :filter_on_b and not :filter_on_a then b=:b
by EdwardDiego 5y ago
select * from foo
where case
when :filter_on_a and not :filter_on_b then a=:a
when :filter_on_b and not :filter_on_a then b=:b
when :filter_on_a and :filter_on_b then a=:a and b=:b
else true
end
Should preserve all your semantics. I can't remember if Python DBAPI handles named parameters, so let's pretend it does and the colon-prefixed parameters are in the right syntax.
cur.execute("above query", filter_on_a=bool(a), filter_on_b=bool(b), a=a, b=b)
Whether the more complex SQL is worth it really depends on your use case.