big "not in" subqueries can be notoriously slow on some well known databases - I had this problem 4 years ago on Sybase. The answers above do not solve principal problem - eliminate need for NOT IN subquery - indexing helps only so much. A much faster code would be something like this (using Transact SQL here):
select ClientID,DeleteFlag=1 into #temp from tblThat
update #temp set DeleteFlag=0
from #temp T,tblThis T2
where T2.ClientID=T.ClientID
delete tblThis from
#temp T,tblThis T2
where T2.ClientID=T.ClientID
and DeleteFlag=1
drop table #temp
Now, this way we avoided "not in" logic completely and only use normal simple joins that every good DB does well.
Notes:
0. There should be good indecies on tblThis.ClientID and tblThat.ClientID
1. I did not use distincts on purpose, this will give big performance benefits if overall "uniqueness" of tableThat is quiet high (but does not have to be 100%). You can even be smart to check built in DB stats to make decision if that particular query would run better off with distinct. Otherwise first query would select distinct CliendIDs from tblThat
I must add that DB2 does appear to do the same thing behind scenes - something every database should do in similar situations.
PerlOfWisdom: stick to yer hashes in Perl -- you will laugh but I used this approach to get some slow SQL queries to run well fast until I mastered art of SQL opts
