I've got a query like the one below:
Select ser.key
From dbo.Enrlmt ser
Where ser.wd >= @FromDate AND ser.wd <= @ThrouDate AND
ser.EnrlmtStatCode = '4321' AND
ser.StuExitCatgCode in ('1','2','3','4','5','6','7') AND
ser.Key not in (select Key
from Enrlmt ser2
where ser2.StartDate <= @AsOfDate
AND ser2.StartDate > ser.wd
AND ser2.EnrlmtStatCode = '4321')
That is extremely slow due to the "NOT IN" clause. I tried rewriting it using a left outer join so that it looked like:
Select ser.key
From dbo.Enrlmt ser
LEFT JOIN dbo.Enrlmt ser2 ON ser.key = ser2.key
AND ser2.StartDate <= @AsOfDate
AND ser2.StartDate > ser.wd
AND ser2.EnrlmtStatCode = '4321'
Where ser2.key is null
AND ser.wd >= @FromDate
AND ser.wd <= @ThrouDate
AND ser.EnrlmtStatCode = '4321'
AND ser.StuExitCatgCode in ('1','2','3','4','5','6','7')
Which is much faster but the results don't match up. Am i doing something wrong with this rewrite? Is there a better way to do this?