Hey all... I've been gone quite awhile and am now in need of a little assistance. I have a select with 5 tables one of which, T1, has a little over 3 million rows. The following query (actual field and table names changed to protect the innocent) runs for about 20 minutes.DECLARE @Start_Date datetimeDECLARE @End_Date datetimeSET @Start_Date = '2/16/2004'SET @End_Date = '2/29/2004'SELECT T1.Field1, T2.Field2FROM Table1 AS T1 INNER JOIN Table2 AS T2 ON ( T2.[ID] = T1.[ID]) INNER JOIN Table3 AS T3 ON ( T3.[ID] = T2.[ID] AND T3.Field1 = @Input1 AND T3.Field2 = @Input2 ) INNER JOIN Table4 AS T4 ON ( T4.[ID] = T1.[ID] AND T4.Field1 = @Input3 ) INNER JOIN T5 AS T5 ON ( T5.[ID] = T3.[ID2])WHERE T1.DateField >= @Start_Date AND T1.DateField <= @End_Date
If I change the where clause to this... WHERE T1.DateField >= '2/16/2004' AND T1.DateField <= '2/29/2004 11:59:59 PM'
... it runs in about 20 seconds.The two selects generate completely different query plans and I don't understand why. The plan for the first version performs all of the joins and then applies the date filter to the entire record set. This causes SQL Server to have to process about 250,000 rows. The second version of the query with the hard coded dates applies the date filter right away so it only has to look at about 4,500 rows. Any thoughts or comments on this behavior would be greatly appreciated. There is a clustered index on an ID field in T1 and a non clustered index on T1.DateField. Please let me know if you need any further details.Thanks!Jeff Banschbach, MCDBA