# Aggregation Operations in SQL Query Execution
> [!Note]
> Efficient aggregation in SQL engines is driven by selecting the appropriate algorithm—**[[Stream Aggregate]]** or **[[Hash Aggregate]]**—while managing **memory usage** to prevent spills and supporting **aggregation functions** like **SUM**, **AVG**, **MAX** alongside **GROUP BY** and **DISTINCT**.
Aggregation operations are fundamental for summarizing data sets, delivering either a singular result or multiple grouped values based on specified keys. The **[[Stream Aggregate]]** approach leverages ordered input by scanning rows sequentially and producing an output each time the grouping key changes, making it highly efficient when data is already sorted. In contrast, the **[[Hash Aggregate]]** method builds an in-memory hash table, which is ideal for processing large volumes of unsorted data without prior ordering.
Both aggregation algorithms depend heavily on **memory usage**, as both the hashing and sorting phases can consume significant resources and, if memory limits are exceeded, may spill intermediate data to tempdb. At the core of these operations lie a set of **aggregation functions**—including **SUM**, **AVG**, and **MAX**—which are evaluated during execution, especially when queries employ **GROUP BY** clauses or the **DISTINCT** modifier to eliminate duplicates.
---
## References
- Korotkevitch, D. (2022). _SQL Server advanced troubleshooting and performance tuning: Best practices and techniques_. O’Reilly Media.
- Nevarez, B. (2022). _SQL Server query tuning and optimization: Optimize Microsoft SQL Server 2022 queries and applications_. Packt Publishing.