> [!NOTE] Merge Append > <table> > <tr> > <td width="25%"><img src="assets/ex_mergeappend.png"></td> > <td>Merges multiple pre-sorted result sets while preserving the sort order.</td> > </tr> > </table> > > ```sql > -- Merging two sorted index scans with UNION ALL + ORDER BY > EXPLAIN (ANALYZE, COSTS, BUFFERS, VERBOSE) > SELECT * FROM (SELECT id FROM animals WHERE id < 100 ORDER BY id) s1 > UNION ALL > SELECT * FROM (SELECT id FROM animals WHERE id >= 100 AND id < 200 ORDER BY id) s2 > ORDER BY id; > ``` > > ![MergeAppend Plan Tree](assets/plan_tree_op_merge_append.svg) > > ```text > Merge Append (cost=0.58..14.30 rows=199 width=4) (actual time=0.006..0.018 rows=199 loops=1) > Sort Key: animals.id > Buffers: shared hit=6 > -> Index Only Scan using animals_pkey on public.animals (cost=0.29..6.02 rows=99 width=4) (actual time=0.002..0.005 rows=99 loops=1) > Output: animals.id > Index Cond: (animals.id < 100) > Heap Fetches: 0 > Buffers: shared hit=3 > -> Index Only Scan using animals_pkey on public.animals animals_1 (cost=0.29..6.29 rows=100 width=4) (actual time=0.003..0.006 rows=100 loops=1) > Output: animals_1.id > Index Cond: ((animals_1.id >= 100) AND (animals_1.id < 200)) > Heap Fetches: 0 > Buffers: shared hit=3 > Planning: > Buffers: shared hit=83 > Planning Time: 0.255 ms > Execution Time: 0.054 ms > ``` > > ![Merge Append measured plan performance signature](assets/trace_op_merge_append.svg) > > <table> > <tr> > <td rowspan="2" width="25%"><img src="assets/ex_merge_append.svg"></td> > <td><b>Performance</b></td><td>High performance as it uses a tournament tree or heap to merge pre-sorted inputs.</td> > </tr> > <tr><td><b>Cost</b></td><td>Sum of sorted subquery costs.</td></tr> > </table>