> **Window Agg** > <table> > <tr> > <td width="25%"><img src="assets/ex_window_aggregate.png"></td> > <td>Computes window functions (e.g., <code>ROW_NUMBER()</code>, <code>RANK()</code>). It requires the input set to be partitioned and sorted, allowing the engine to slide a 'window' over the rows and calculate values relative to the current row.</td> > </tr> > </table> > > ```sql > -- Calculating row numbers over a sorted set > EXPLAIN (ANALYZE, COSTS, BUFFERS, VERBOSE) > SELECT name, row_number() OVER (ORDER BY name) > FROM animals; > ``` > > ![WindowAgg Plan Tree](assets/plan_tree_op_window_agg.svg) > > <!-- literal-explain-plan > Captured EXPLAIN provenance for the adjacent reader-facing visual plan. > Canonical capture metadata lives in scratch/actual_operation_plans.json. > > WindowAgg (cost=838.40..1013.39 rows=10000 width=19) (actual time=4.593..5.606 rows=10000 loops=1) > Output: name, row_number() OVER (?) > Buffers: shared hit=77 > -> Sort (cost=838.39..863.39 rows=10000 width=11) (actual time=4.586..4.785 rows=10000 loops=1) > Output: name > Sort Key: animals.name > Sort Method: quicksort Memory: 385kB > Buffers: shared hit=77 > -> Seq Scan on public.animals (cost=0.00..174.00 rows=10000 width=11) (actual time=0.003..0.325 rows=10000 loops=1) > Output: name > Buffers: shared hit=74 > Planning: > Buffers: shared hit=86 > Planning Time: 0.179 ms > Execution Time: 5.810 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. > --> > > ![Window Agg separate raw capture](assets/trace_op_window_agg.svg) > > <table> > <tr> > <td rowspan="2" width="25%"><img src="assets/ex_window_aggregate.svg"></td> > <td><b>Performance</b></td><td>CPU-intensive as it must track state across multiple rows; memory-intensive if using large partitions.</td> > </tr> > <tr><td><b>Cost</b></td><td><code>window function cost * number of rows</code></td></tr> > </table>