I am using this condition as part of my where clause: exists (select * from PRPB PB where PA.mid = PB.mid and (@inpo is null or PB.inpo = @inpo)) order by price
.
While testing non-null @inpo values, I noticed the query runs much faster when I instead use this condition: exists (select * from PRPB PB where PA.mid = PB.mid and (PB.inpo = @inpo)) order by price
. That this causes a non-neglible speed difference suggests that I will be forced to use two separate queries with an if statement in order to decide whether to filter out by @inpo or not. This strikes me as a bad thing, since it means a lot of code repetition.
Things I have tried:
- Creating a bit that stores whether @inpo is non-null and comparing with that.
- Moving the nullity check to the left of the exists statement and doing an or with the whole thing (this slows things down a lot, which surprises me).
- Moving the nullity check to the leftmost of the where class and oring it with all the clauses (this also slows things down a lot, which doesn't surprise me at all, since it means the nullity check always happens, regardless of whether or not PA.mid = PB.mid).
My goal is to have it perform this check much faster without having two copies of my query.
Is this possible? If not, why not? If so, how?
Note: See also a 2nd related question here.