A couple of suggestions:
Don't use
SELECT *
- just list the columns you actually need.Use
EXISTS
rather thanIN
(since the former can short circuit):SELECT cols FROM dbo.SomeTable AS s WHERE EXISTS (SELECT 1 FROM @p1 WHERE ID = s.SomeForeignId) OR SomeForeignId IS NULL;
The above may still end up with a concatenation (which essentially means a
UNION
), but you may try writing your ownUNION ALL
to avoid theOR
:SELECT cols FROM dbo.SomeTable AS s WHERE EXISTS (SELECT 1 FROM @p1 WHERE ID = s.SomeForeignId) UNION ALL SELECT cols FROM dbo.SomeTable WHERE SomeForeignId IS NULL;
What's troubling me is that either of your existing variations take almost two seconds. Please be sure that there is an index on SomeTable.SomeForeignId
- not just a foreign key constraint, but an actual non-clustered index. It's not clear in your question that this is the index you get a seek on.