SQL statement optimization uses exists instead of in, with not exists instead of the statement _mssql
Source: Internet
Author: User
In many base table based queries, a join to another table is often required to satisfy one condition. In this case, using EXISTS (or not EXISTS) usually increases the efficiency of the query. In a subquery, the NOT IN clause performs an internal sort and merge. In either case, not in is the least efficient (because it performs a full table traversal of the table in the subquery). In order to avoid using not in, we can rewrite it as an outer join (Outer joins) or not EXISTS.
Such as
I want to query for redundant data in the Sendorder table (no data connected to Reg_person or worksite)
Sql= "Select Sendorder.id,sendorder.reads,sendorder.addtime from Sendorder where sendorder.person_id not in" (Select User _id from Reg_person) or sendorder.worksite_id isn't in (select ID from worksite) ORDER by sendorder.addtime Desc "
Program execution time: 40109.38 ms
Sql= "Select Sendorder.id,sendorder.reads,sendorder.addtime from Sendorder where not EXISTS (select ID from Reg_person whe Re reg_person.user_id=sendorder.person_id) or not EXISTS (SELECT IDs from worksite where Worksite.id=sendorder.worksite_ ID) Order BY sendorder.addtime Desc "
Program execution time: 8531.25 ms
It's obvious that using not exists is much more efficient.
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.