Today, we will have a look into SQL Server aggregate operator – Stream Aggregate. This operator used to group some rows by one or more columns and to calculate any aggregation expressions specified in query statement(s).
Some common types of expressions are SUM, AVG, COUNT, MAX, MIN etc. When we use any of these functions we will probably see a stream aggregate operation on the plan. This operator can be very fast as it requires an input that already been ordered by the column specified in GROUP BY clause else it may force query optimizer to use SORT operator or can use a pre-sorted data from index seek or scan.
Enough theory? Ok, let us see this in action using following statement;
USE [AdventureWorks2012] SELECT AVG(Product.SafetyStockLevel) FROM [Production].[Product]
To understand what Expr1004 and Expr1005 are, let us decode query plan in text.
USE [AdventureWorks2012] --Step 1 SET SHOWPLAN_TEXT ON --Step 2 SELECT AVG(Product.SafetyStockLevel) FROM [Production].[Product] --Step 3 SET SHOWPLAN_TEXT OFF
We can obtain same information from graphical plan by selecting Stream Aggregate operator then pressing F4.
In order to calculate AVG, the stream aggregate is computing both count and sum and the results are stored in the computed expressions Expr1004 and Expr1005 respectively. Compute scalar operator (we are going to cover this operator in future) verifies there is no division by zero using a case statement.
We are going to discuss more on this operator on tomorrow’s post, stay tuned.