SQL Server Performance optimizations: subquery VS joins

Source: Internet
Author: User

Create a table in the database as follows, and count the number of Tasknote for each task.

The first of these solutions:

SelectT.taskid, (Select Count(n.id) fromTasknote NwhereN.taskid=T.taskid)'Notes',--exec every row(Select Count(n.comment) fromTasknote NwhereN.taskid=T.taskid)'Notes1',--exec every row(Select Count(N.createdtime) fromTasknote NwhereN.taskid=T.taskid)'Notes2'  --exec every row fromTask T

The sub-query above is just as an example, the actual use may need to count each time each task corresponding comment number, here steal a lazy (ˇ?ˇ) like this to love lazy cat ~

The execution plan is as follows: (very complex, each subquery needs to be executed once, the visible performance is also not very good)

This way, easy to understand, readability is high, but when the sub-query when the amount of data is large, because each row will execute embedded subquery, can cause slow performance.

Second Solution:

--using GROUP BY and table joinsSelectT.taskid,Count(n.id)'Notes',       Count(n.comment)'Notes1',       Count(N.createdtime)'Notes2' fromTask T Left Jointasknote N on     IsNull(T.taskid,'__')= IsNull(N.taskid,'__')Group  byT.taskid

The execution plan is as follows: (this looks much simpler than the above, imagine that performance will improve)

When the amount of data is large, the performance aspect of using the left join will be greatly improved, note that when on, the null value is converted using IsNull.

The two methods can be very different when the data volume performance is not very large, but when the data is large and the sub-query nesting complex may need to carefully consider.

At work, there is a big difference in the performance gap when dealing with big data and complex statistical data. Take this log as a record, warning!

Fighting for me,my Dear Darling,my family, ~o (∩_∩) o~.

SQL Server Performance optimizations: subquery VS joins

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.