Not sure where to start on this one -- not sure if the problem is that I\'m fooling the query optimizer, or if it\'s something intrinsic to the way indexes work when nulls a
You have a combination of issues, most likely
But without seeing the plans, these are educated guesses.
Parameter sniffing
... of the default "NULL". Try it with different defaults, say -1 or no default.
The @ID = -1 with a default of NULL and parameter sniffing = trivial check, so it's faster.
You could also try OPTIMISE FOR UNKNOWN in SQL Server 2008
The OR operator
Some ideas..
If the columns is not nullable, in most cases the optimiser ignores the condition
st.ID = ISNULL(@ID, st.ID)
Also, you can use IF statement
IF @ID IS NULL
SELECT ... FROM...
ELSE
SELECT ... FROM... WHERE st.ID
Or UNION ALL in a similar fashion.
Personally, I'd use parameter masking (always) and ISNULL in most cases (I'd try it first)
alter procedure SomeProc
@ID int = NULL
AS
declare @maskID int
select @maskID = @ID
...