Hi Friends,
I hope you liked previous blog posts on SQL Server aggregate operator – Stream Aggregate Part1 and Part2. In today’s post, we are going to see that this operator can also use an index to have its input sorted.
USE [AdventureWorks2012] SELECT SalesOrderDetail.SalesOrderID,SUM(SalesOrderDetail.LineTotal) AS 'SUM' FROM Sales.SalesOrderDetail GROUP BY SalesOrderDetail.SalesOrderID
There is no need to have sort operation as clustered index scan produce the data sorted by SalesOrderDetail.SalesOrderID column. Stream aggregate operator will consume sorted data and it will calculate sum of SalesOrderDetail.LineTotal column group wise. We can have more clarity when query plan is decoded in text.
USE [AdventureWorks2012] --Step 1 SET SHOWPLAN_TEXT ON --Step 2 SELECT SalesOrderDetail.SalesOrderID,SUM(SalesOrderDetail.LineTotal) AS 'SUM' FROM Sales.SalesOrderDetail GROUP BY SalesOrderDetail.SalesOrderID --Step 3 SET SHOWPLAN_TEXT OFF
Stream Aggregate operator aggregate values based on groups and its logic relies on the fact that input is being sorted using GROUP BY. Algorithm is designed to create a group based on first record then and then initialize aggregate values. Next record is checked to see if they match first group and if so then include it in the first group else create a new one and this process continues until all records are being processed.
I hope this explains how stream aggregate works. I’ll be back tomorrow with another operator, stay tuned!
Regards,
Kanchan
Like us on FaceBook | Join the fastest growing SQL Server group on FaceBook | Follow me on Twitter | Follow me on FaceBook