> [!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 parallel_setup_cost = 0; > SET parallel_tuple_cost = 0; > SET enable_indexscan = off; > SET parallel_leader_participation = off; > > EXPLAIN (ANALYZE, COSTS, BUFFERS, VERBOSE) > SELECT * FROM animals ORDER BY id; > ``` > > ![GatherMerge Plan Tree](assets/plan_tree_op_gather_merge.svg) > > ```text > Gather Merge (cost=366.23..463.52 rows=8334 width=27) (actual time=2.324..2.919 rows=10000 loops=1) > Output: id, name, species_id, created_at > Workers Planned: 2 > Workers Launched: 2 > Buffers: shared hit=146 > -> Sort (cost=366.20..376.62 rows=4167 width=27) (actual time=0.238..0.303 rows=3333 loops=3) > Output: id, name, species_id, created_at > Sort Key: animals.id > Sort Method: quicksort Memory: 853kB > Buffers: shared hit=146 > Worker 0: actual time=0.023..0.023 rows=0 loops=1 > Sort Method: quicksort Memory: 25kB > Buffers: shared hit=36 > Worker 1: actual time=0.028..0.028 rows=0 loops=1 > Sort Method: quicksort Memory: 25kB > Buffers: shared hit=36 > -> Parallel Seq Scan on public.animals (cost=0.00..115.67 rows=4167 width=27) (actual time=0.001..0.106 rows=3333 loops=3) > Output: id, name, species_id, created_at > Buffers: shared hit=74 > Worker 0: actual time=0.000..0.000 rows=0 loops=1 > Worker 1: actual time=0.000..0.000 rows=0 loops=1 > Planning: > Buffers: shared hit=83 > Planning Time: 0.171 ms > Execution Time: 3.125 ms > ``` > > ![Gather Merge measured plan performance signature](assets/trace_op_gather_merge.svg) > > <table> > <tr> > <td rowspan="2" 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>Cost</b></td><td><code>parallel worker cost + inter-process communication cost</code></td></tr> > </table>