I learned a trick some time ago from a DBA friend to speed up some SQL queries. I remember that he mentioned that it had something to do with how SQL Server compiles the query and that the query path is forced to use an indexed value.
Here is my original request (takes 20 seconds):
select Part.Id as PartId, Location.Id as LocationId FROM Part, PartEvent PartEventOuter, District, Location WHERE PartEventOuter.EventType = '600' AND PartEventOuter.AddressId = Location.AddressId AND Part.DistrictId = District.Id AND Part.PartTypeId = 15 AND District.SubRegionId = 11 AND PartEventOuter.PartId = Part.Id AND PartEventOuter.EventDateTime <= '4/28/2009 4:30pm' AND NOT EXISTS ( SELECT PartEventInner.EventDateTime FROM PartEvent PartEventInner WHERE PartEventInner.PartId = PartEventOuter.PartId AND PartEventInner.EventDateTime > PartEventOuter.EventDateTime AND PartEventInner.EventDateTime <= '4/30/2009 4:00pm')
Here is the βoptimizedβ query (less than 1 second):
select Part.Id as PartId, Location.Id as LocationId FROM Part, PartEvent PartEventOuter, District, Location WHERE PartEventOuter.EventType = '600' AND PartEventOuter.AddressId = Location.AddressId AND Part.DistrictId = District.Id AND Part.PartTypeId = 15 AND District.SubRegionId = 11 AND PartEventOuter.PartId = Part.Id AND PartEventOuter.EventDateTime <= '4/28/2009 4:30pm' AND NOT EXISTS ( SELECT PartEventInner.EventDateTime FROM PartEvent PartEventInner WHERE PartEventInner.PartId = PartEventOuter.PartId **AND EventType = EventType** AND PartEventInner.EventDateTime > PartEventOuter.EventDateTime AND PartEventInner.EventDateTime <= '4/30/2009 4:00pm')
Can someone explain in detail why this works much faster? I'm just trying to better understand this.
source share