I need to run a query to compare two tables and return the records that are not in the second table. The tricky part is that the link between the two table is conditional. I have multiple sources feeding into Table2 and that is then feeding into Table1. I've tried using a join, but that is not any faster than what I have below. The tables have about 50k records in them. This query takes about 1.5 minutes to complete. I'm hoping to get it to about a few second. Table1 and Table2 already have indexes on these fields. The DB is running on compatibility Level SQL2008.
This query takes about 1.5 minutes:
select *
from Table1 t1
where not exists (select *
from Table2 t2
where t2.seedID = case t2.SeedSource when 'SeedSource1' then t1.SeedSource1
when 'SeedSource2' then t1.SeedSource2
when 'SeedSource3' then t1.SeedSource3
when 'SeedSource4' then t1.SeedSource4
when 'SeedSource5' then t1.SeedSource5 end)
This query takes over five minutes:
select d.*
from Tabel1 t1 left join
Table2 t2 on t2.seedID = case t2.SeedSource when 'SeedSource1' then t1.SeedSource1
when 'SeedSource2' then t1.SeedSource2
when 'SeedSource3' then t1.SeedSource3
when 'SeedSource4' then t1.SeedSource4
when 'SeedSource5' then t1.SeedSource5 end
where t2.seedID is NULL
Any help would be greatly appreciated.