I have a problem where I need to find records that either have a measurement that matches a value, or do not have that measurement at all. I solved that problem with three or four different approaches, using JOIN
s, using NOT IN
and using NOT EXISTS
. However, the query ended up being extremely slow every time. I then tried splitting the query in two, and they both run very fast (three seconds). But combining the queries using OR
takes more than five minutes.
Reading on SO I tried UNION
, which is very fast, but very inconvenient for the script I am using.
So two questions:
- Why is
UNION
so much faster? (Or why isOR
so slow)? - Is there any way I can force
MSSQL
to use a different approach for theOR
statement that is fast?