> [!NOTE] Aggregate > <table> > <tr> > <td width="25%"><img src="assets/ex_aggregate.png"></td> > <td>The engine's mechanism for collapsing multiple rows into a single result (e.g., SUM, COUNT). It can operate by sorting the input (GroupAggregate) or by building an in-memory hash table (HashAggregate) to keep track of running totals for each group.</td> > </tr> > </table> > > ```sql > -- Counting animals grouped by species > EXPLAIN (ANALYZE, COSTS, BUFFERS, VERBOSE) > SELECT species_id, count(*) > FROM animals > GROUP BY species_id; > ``` > > ![Aggregate Plan Tree](assets/plan_tree_op_aggregate.svg) > > ```text > HashAggregate (cost=224.00..224.05 rows=5 width=12) (actual time=0.767..0.768 rows=5 loops=1) > Output: species_id, count(*) > Group Key: animals.species_id > Batches: 1 Memory Usage: 24kB > Buffers: shared hit=74 > -> Seq Scan on public.animals (cost=0.00..174.00 rows=10000 width=4) (actual time=0.003..0.290 rows=10000 loops=1) > Output: id, name, species_id, created_at > Buffers: shared hit=74 > Planning: > Buffers: shared hit=77 > Planning Time: 0.187 ms > Execution Time: 0.793 ms > ``` > > ![Aggregate measured plan performance signature](assets/trace_op_aggregate.svg) > > <table> > <tr> > <td rowspan="2" width="25%"><img src="assets/ex_aggregate.svg"></td> > <td><b>Performance</b></td><td>CPU-intensive for complex aggregations; memory-intensive if using HashAggregate.</td> > </tr> > <tr><td><b>Cost</b></td><td><code>cpu_tuple_cost * number of tuples + cpu_operator_cost * number of groups</code></td></tr> > </table>