> [!NOTE] 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; > ``` > > ```text > WindowAgg (cost=1.29..852.29 rows=20000 width=19) (actual time=1.014..3.155 rows=20000 loops=1) > Output: name, row_number() OVER (?) > Buffers: shared hit=63 > -> Index Only Scan using idx_animals_name on public.animals (...) > ``` > > <table> > <tr> > <td rowspan="5" 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>Factors</b></td><td>Number of rows, the complexity of the window function, and the size of the window frame.</td></tr> > <tr><td><b>Cost</b></td><td><code>window function cost * number of rows</code></td></tr> > <tr><td><b>Operates on</b></td><td><a href="Structures/Result Set">Result Set</a></td></tr> > <tr><td><b>Workloads</b></td><td><a href="Workloads/IO/BufFile/BufFileRead">IO: BufFileRead</a>, <a href="Workloads/IO/BufFile/BufFileWrite">IO: BufFileWrite</a>, <a href="Workloads/LWLock/Buffers/BufferContent">LWLock: BufferContent</a></td></tr> > <tr><td colspan="3"><b>Description</b>: Computes window functions.</td></tr> > </table>