> [!NOTE] Gather Merge > <table> > <tr> > <td width="25%"><img src="assets/ex_gathermerge.png"></td> > <td>A specialized version of the Gather node that maintains the sort order of the results arriving from parallel workers. It performs a multi-way merge as it receives rows, ensuring the leader process sees a single, sorted stream.</td> > </tr> > </table> > > ```sql > -- Forcing a parallel sort and merge > SET max_parallel_workers_per_gather = 2; > SET min_parallel_table_scan_size = 0; > SET enable_indexscan = off; > > EXPLAIN (ANALYZE, COSTS, BUFFERS, VERBOSE) > SELECT * FROM animals ORDER BY id; > ``` > > ```text > Gather Merge (cost=774.03..968.60 rows=16666 width=27) (actual time=4.327..5.298 rows=20000 loops=1) > Output: id, name, species_id, created_at > Workers Planned: 2 > Workers Launched: 2 > Buffers: shared hit=220 > -> Sort (cost=774.00..794.84 rows=8333 width=27) (actual time=1.444..1.558 rows=6667 loops=3) > Output: id, name, species_id, created_at > Sort Key: animals.id > ... > ``` > > <table> > <tr> > <td rowspan="5" width="25%"><img src="assets/ex_gather_merge.svg"></td> > <td><b>Performance</b></td><td>High overhead due to Inter-Process Communication (IPC), but enables linear scaling for CPU-bound sorts.</td> > </tr> > <tr><td><b>Factors</b></td><td>Number of workers, communication overhead, and the cost of the child sort nodes.</td></tr> > <tr><td><b>Cost</b></td><td><code>parallel worker cost + inter-process communication cost</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/IPC/Parallel/ExecuteGather">IPC: ExecuteGather</a>, <a href="Workloads/IPC/Parallel/ParallelFinish">IPC: ParallelFinish</a>, <a href="Workloads/LWLock/Parallel/ParallelQueryDSA">LWLock: ParallelQueryDSA</a>, <a href="Workloads/LWLock/Buffers/SharedTupleStore">LWLock: SharedTupleStore</a></td></tr> > <tr><td colspan="3"><b>Description</b>: Collects and merges sorted results from parallel workers.</td></tr> > </table>