SQL Server Query Optimization – Date Range in WHERE Clause and Execution Plan Issues

datetimeexecution-plansql server

I have the following query in SQL server:

declare @timestamp_start date = getdate() - 1
declare @timestamp_end date = getdate()

SELECT  
    my_date = a.itemTimestamp
FROM
    my_table a with(nolock)
WHERE 
    (@timestamp_start is null OR a.itemTimestamp >= @timestamp_start)
    AND (@timestamp_end is null OR a.itemTimestamp < @timestamp_end)

It's extremely slow (90s for < 2000 records), because the execution plan uses the clustered index of the PK column for 'my_table':

enter image description here

Why is this happening and how can I optimize the query performance?

Best Answer

What is the datatype of itemTimestamp? Is that column indexed? Is the column nullable?

Assuming the answers are datetime, Yes, and No respectively you might consider

WHERE  a.itemTimestamp >= isnull(@timestamp_start, '17530101')
       AND a.itemTimestamp < isnull(@timestamp_end, '99991231') 

If you were to change to datetime2 and actually store dates before 1753 you would need to change the lower bound condition to 00010101. This also won't bring back dates matching the higher bound of 9999-12-31 - but in the real world this is unlikely to cause a problem.