Background
I have two tables - one is updated each day with new data (failed deadline) and one is continually added and deleted from dependent on the other (live table).
The way it works is that if the persons allocated work appears in the 'failed deadline' table, then add to the 'live' table. If the persons allocated work is then not on the 'failed deadline' table the next day, remove from the 'live' table.
The two biggest issues here are that whilst the ID number of the work is an easy check, it also has to check to see if the work is still allocated to the same employee, so that if it changes hands it doesn't count against them.
The problem I'm facing is that the delete portion of the code seems to run over 3,000 rows and return about 300 just fine, but this SQL statement is taking over 4 minutes and 30 seconds to execute. What is the most efficient way of writing this statement? My gut instinct is telling me that the two statements are different and combining them is the issue.
DELETE FROM [LiveTable] WHERE [WorkID] NOT IN (SELECT [WorkID] FROM [FailedDeadline]) OR [LiveTable].[EmployeeID] <> (SELECT [EmployeeID] FROM [FailedDeadline] as fd WHERE [LiveTable].[WorkID] = fd.[WorkID]);
NOT EXISTSand aNOT INaren't going to perform too differently, however, aNOT INdoes have problems withNULLs, so you probably want the latter. For the second subquery, perhaps aLEFT JOINmight be more performant, but it's unlikely to make a big dent.WHERE NOT INwithWHERE NOT EXISTS, but SQL Server probably would already have optimized it under the hood. Beyond that, have a look at this canonical DBA question which discusses ways to improve the speed of a delete.NOT INcertainly can perform much worse thanNOT EXISTS- especially if the columns being compared areNULL-able on both sides. Because SQL Server then has to add a load of extra operators to the plan to deal with this that can make things significantly more expensive. See for example sqlinthewild.co.za/index.php/2010/02/18/not-exists-vs-not-in (logical reads on SmallerTable 500011 and elapsed time = 825 ms vs logical reads 9 and elapsed time = 228 ms) and another look at it here stackoverflow.com/a/11074428/73226