The database was restarted on Sunday, just looking at the optimized results. By the way, look for new SQL statements to be optimized.
Just found several similar statements, as shown below
Select * From tablea where id not in (select ID from tableb)
From execution time 20 seconds ~ 70 seconds.
Start Analysis
First, whether to use the index. Because both IDs are primary keys, there is no index problem.
Next, we analyze the index and find that although these two IDs are primary keys, they are not clustered indexes, and they are completely out of order generated by newid, therefore, these two tables are useless in indexing, because they are all unordered.
In another way, if the two IDs are sorted and the number of records is not small, will the association be fast? Fortunately, sqlserver provides the hint prompt for merge join. Try it.
Select * From tablea where id not in (select ID from tableb) option (merge join );
The following error occurs after execution:
Message 8622, level 16, state 1, 1st rows
The query processor fails to generate a query plan because a prompt is defined in this query. Please submit the query again, and do not specify any prompts in the query, or use set forceplan.
Check the following documents, that is, this statement does not support option (merge join );
Switch to not exists and try again to see if the effect will be better.
Select * From tablea where not exists (select 1 from tableb where tablea. ID = tableb. ID)
After passing the test, it is found that the speed is improved a little
Finally, add option (merge join). Try it and it turns to 0 seconds.
Select * From tablea where not exists (select 1 from tableb where tablea. ID = tableb. ID) option (merge join );
The optimization was successful.
Summary:
Not all related tables must be indexed (or aggregated indexes). You can try the SQL Server Query prompt later.