SQL Server performance optimization query prompt

Source: Internet
Author: User
Tags sql server query

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.