David Rowley 66c0185a3d Allow planner to use Merge Append to efficiently implement UNION
Until now, UNION queries have often been suboptimal as the planner has
only ever considered using an Append node and making the results unique
by either using a Hash Aggregate, or by Sorting the entire Append result
and running it through the Unique operator.  Both of these methods
always require reading all rows from the union subqueries.

Here we adjust the union planner so that it can request that each subquery
produce results in target list order so that these can be Merge Appended
together and made unique with a Unique node.  This can improve performance
significantly as the union child can make use of the likes of btree
indexes and/or Merge Joins to provide the top-level UNION with presorted
input.  This is especially good if the top-level UNION contains a LIMIT
node that limits the output rows to a small subset of the unioned rows as
cheap startup plans can be used.

Author: David Rowley
Reviewed-by: Richard Guo, Andy Fan
Discussion: https://postgr.es/m/CAApHDvpb_63XQodmxKUF8vb9M7CxyUyT4sWvEgqeQU-GB7QFoQ@mail.gmail.com
2024-03-25 14:31:14 +13:00

59 lines
1.7 KiB
C

/*-------------------------------------------------------------------------
*
* prep.h
* prototypes for files in optimizer/prep/
*
*
* Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* src/include/optimizer/prep.h
*
*-------------------------------------------------------------------------
*/
#ifndef PREP_H
#define PREP_H
#include "nodes/pathnodes.h"
#include "nodes/plannodes.h"
/*
* prototypes for prepjointree.c
*/
extern void transform_MERGE_to_join(Query *parse);
extern void replace_empty_jointree(Query *parse);
extern void pull_up_sublinks(PlannerInfo *root);
extern void preprocess_function_rtes(PlannerInfo *root);
extern void pull_up_subqueries(PlannerInfo *root);
extern void flatten_simple_union_all(PlannerInfo *root);
extern void reduce_outer_joins(PlannerInfo *root);
extern void remove_useless_result_rtes(PlannerInfo *root);
extern Relids get_relids_in_jointree(Node *jtnode, bool include_outer_joins,
bool include_inner_joins);
extern Relids get_relids_for_join(Query *query, int joinrelid);
/*
* prototypes for preptlist.c
*/
extern void preprocess_targetlist(PlannerInfo *root);
extern List *extract_update_targetlist_colnos(List *tlist);
extern PlanRowMark *get_plan_rowmark(List *rowmarks, Index rtindex);
/*
* prototypes for prepagg.c
*/
extern void get_agg_clause_costs(PlannerInfo *root, AggSplit aggsplit,
AggClauseCosts *costs);
extern void preprocess_aggrefs(PlannerInfo *root, Node *clause);
/*
* prototypes for prepunion.c
*/
extern RelOptInfo *plan_set_operations(PlannerInfo *root);
extern bool set_operation_ordered_results_useful(SetOperationStmt *setop);
#endif /* PREP_H */