Do Stream Aggregate Operator Always Need Sort Operator? – Interview Question of the Week #240

Question: Does Stream Aggregate always need a Sort operator? No. Grouped stream aggregation needs appropriately ordered groups, but the order can come from another operator. A scalar aggregate over the whole input has no grouping order to establish.

An already ordered line of containers travels along a conveyor

After my Stream Aggregate versus Gather Streams article, a health-check client questioned my phrase that Stream Aggregate is often seen with Sort. Could it appear without one? Absolutely.

SELECT MAX(i.BillToCustomerID) AS TotalRows
FROM WideWorldImporters.Sales.Invoices AS i;
SELECT SUM(i.BillToCustomerID) AS TotalRows
FROM WideWorldImporters.Sales.Invoices AS i;
SELECT AVG(i.BillToCustomerID) AS TotalRows
FROM WideWorldImporters.Sales.Invoices AS i;
Original MAX SUM and AVG actual plans contain Stream Aggregate and no Sort
The original plans match the three queries. They also contain scans, and some contain Compute Scalar or Top. Stream Aggregate is not the only operator.

These examples have no GROUP BY. Every input row belongs to one overall aggregate, so neither SUM nor AVG needs the input sorted by customer ID. The original explanation attributed all three missing sorts to already ordered input; the scalar-aggregate distinction is the stronger answer.

For GROUP BY BillToCustomerID, Stream Aggregate needs each customer’s rows together. An ordered index access may provide that grouping order without a separate Sort. If the plan can’t obtain it that way, it may sort first or choose a different aggregation algorithm.

MAX can sometimes use an ordered access plus Top to avoid reading every row, as in the historical first plan. The aggregate names and TotalRows aliases are retained to match the original capture, but these values are not row counts.

Your server’s plan may differ with indexes, compatibility level and data. Read the actual operators rather than treating this capture as a guaranteed plan shape. Also, a Stream Aggregate does not promise the final result ordering; use ORDER BY when that is required.

Related: CASE in WHERE.

Want to try this yourself? Here is how to install WideWorldImporters.

Published by Pinal Dave on SQLAuthority. More of my work at pinaldave.com.


Discover more from SQL Authority with Pinal Dave

Subscribe to get the latest posts sent to your email.

Execution Plan, Parallel, SQL Operator, SQL Scripts, SQL Server
Previous Post
How to Use a CASE Statement in the WHERE Clause? – Interview Question of the Week #239
Next Post
How to Use Multiple Hints Together for a Query? – Interview Question of the Week #241

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.