How can I get a query which uses an OR in the WHERE clause to split itself into two queries with a UNION during compilation? If I manually rewrite it, the query using the UNION is 100x faster than the single query, because it can effectively use different indices in each query of the union. Is there any way I can make the optimizer use this approach?
I have a query that looks something like this:
select columnlist
from table1
join table2 on joincond2
join table3 on joincond3
where conditions1
and ((@param1 is null and cond3a) or (cond3b))
Where columnlist, joincond2, joincond3, and conditions1 are all longer expressions. The kicker is that only one of the conditions in the OR is ever true.
I first thought I could just rewrite it to do the union, but then I am repeating columnlist, joincond2, joincond3, and conditions1, which is 20 or so lines of SQL that might need a lot of maintenance in the future. Is there a hint I can supply or some better way to write the WHERE clause? Thanks in advance.