> **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) > > <!-- literal-explain-plan > Captured EXPLAIN provenance for the adjacent reader-facing visual plan. > Canonical capture metadata lives in scratch/actual_operation_plans.json. > > 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 > --> > > > <!-- > Raw-capture provenance — separate run. > SQL, setup, dataset, settings, and scope: artifacts/chapter4_capture_matrix.json. > Target: PostgreSQL 18.x companion fixture. Cache state: uncontrolled. > Boundary: pg_wait_tracer backend execution root; client states are included when the chart shows them. > Fidelity: exact pg_wait_tracer export. Not the adjacent EXPLAIN run; compare state shape, not durations. > --> > > ![Aggregate separate raw capture](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>