1 /*-------------------------------------------------------------------------
4 * The query optimizer external interface.
6 * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/optimizer/plan/planner.c,v 1.163 2003/12/28 21:57:36 tgl Exp $
13 *-------------------------------------------------------------------------
20 #include "catalog/pg_operator.h"
21 #include "catalog/pg_type.h"
22 #include "executor/executor.h"
23 #include "miscadmin.h"
24 #include "nodes/makefuncs.h"
25 #ifdef OPTIMIZER_DEBUG
26 #include "nodes/print.h"
28 #include "optimizer/clauses.h"
29 #include "optimizer/cost.h"
30 #include "optimizer/pathnode.h"
31 #include "optimizer/paths.h"
32 #include "optimizer/planmain.h"
33 #include "optimizer/planner.h"
34 #include "optimizer/prep.h"
35 #include "optimizer/subselect.h"
36 #include "optimizer/tlist.h"
37 #include "optimizer/var.h"
38 #include "parser/analyze.h"
39 #include "parser/parsetree.h"
40 #include "parser/parse_expr.h"
41 #include "parser/parse_oper.h"
42 #include "utils/selfuncs.h"
43 #include "utils/syscache.h"
46 /* Expression kind codes for preprocess_expression */
47 #define EXPRKIND_QUAL 0
48 #define EXPRKIND_TARGET 1
49 #define EXPRKIND_RTFUNC 2
50 #define EXPRKIND_LIMIT 3
51 #define EXPRKIND_ININFO 4
54 static Node *preprocess_expression(Query *parse, Node *expr, int kind);
55 static void preprocess_qual_conditions(Query *parse, Node *jtnode);
56 static Plan *inheritance_planner(Query *parse, List *inheritlist);
57 static Plan *grouping_planner(Query *parse, double tuple_fraction);
58 static bool hash_safe_grouping(Query *parse);
59 static List *make_subplanTargetList(Query *parse, List *tlist,
60 AttrNumber **groupColIdx, bool *need_tlist_eval);
61 static void locate_grouping_columns(Query *parse,
64 AttrNumber *groupColIdx);
65 static List *postprocess_setop_tlist(List *new_tlist, List *orig_tlist);
68 /*****************************************************************************
70 * Query optimizer entry point
72 *****************************************************************************/
74 planner(Query *parse, bool isCursor, int cursorOptions)
76 double tuple_fraction;
78 Index save_PlannerQueryLevel;
79 List *save_PlannerParamList;
82 * The planner can be called recursively (an example is when
83 * eval_const_expressions tries to pre-evaluate an SQL function). So,
84 * these global state variables must be saved and restored.
86 * These vars cannot be moved into the Query structure since their whole
87 * purpose is communication across multiple sub-Queries.
89 * Note we do NOT save and restore PlannerPlanId: it exists to assign
90 * unique IDs to SubPlan nodes, and we want those IDs to be unique for
91 * the life of a backend. Also, PlannerInitPlan is saved/restored in
92 * subquery_planner, not here.
94 save_PlannerQueryLevel = PlannerQueryLevel;
95 save_PlannerParamList = PlannerParamList;
97 /* Initialize state for handling outer-level references and params */
98 PlannerQueryLevel = 0; /* will be 1 in top-level subquery_planner */
99 PlannerParamList = NIL;
101 /* Determine what fraction of the plan is likely to be scanned */
105 * We have no real idea how many tuples the user will ultimately
106 * FETCH from a cursor, but it seems a good bet that he doesn't
107 * want 'em all. Optimize for 10% retrieval (you gotta better
108 * number? Should this be a SETtable parameter?)
110 tuple_fraction = 0.10;
114 /* Default assumption is we need all the tuples */
115 tuple_fraction = 0.0;
118 /* primary planning entry point (may recurse for subqueries) */
119 result_plan = subquery_planner(parse, tuple_fraction);
121 Assert(PlannerQueryLevel == 0);
124 * If creating a plan for a scrollable cursor, make sure it can run
125 * backwards on demand. Add a Material node at the top at need.
127 if (isCursor && (cursorOptions & CURSOR_OPT_SCROLL))
129 if (!ExecSupportsBackwardScan(result_plan))
130 result_plan = materialize_finished_plan(result_plan);
133 /* executor wants to know total number of Params used overall */
134 result_plan->nParamExec = length(PlannerParamList);
136 /* final cleanup of the plan */
137 set_plan_references(result_plan, parse->rtable);
139 /* restore state for outer planner, if any */
140 PlannerQueryLevel = save_PlannerQueryLevel;
141 PlannerParamList = save_PlannerParamList;
147 /*--------------------
149 * Invokes the planner on a subquery. We recurse to here for each
150 * sub-SELECT found in the query tree.
152 * parse is the querytree produced by the parser & rewriter.
153 * tuple_fraction is the fraction of tuples we expect will be retrieved.
154 * tuple_fraction is interpreted as explained for grouping_planner, below.
156 * Basically, this routine does the stuff that should only be done once
157 * per Query object. It then calls grouping_planner. At one time,
158 * grouping_planner could be invoked recursively on the same Query object;
159 * that's not currently true, but we keep the separation between the two
160 * routines anyway, in case we need it again someday.
162 * subquery_planner will be called recursively to handle sub-Query nodes
163 * found within the query's expressions and rangetable.
165 * Returns a query plan.
166 *--------------------
169 subquery_planner(Query *parse, double tuple_fraction)
171 List *saved_initplan = PlannerInitPlan;
172 int saved_planid = PlannerPlanId;
178 /* Set up for a new level of subquery */
180 PlannerInitPlan = NIL;
183 * Look for IN clauses at the top level of WHERE, and transform them
184 * into joins. Note that this step only handles IN clauses originally
185 * at top level of WHERE; if we pull up any subqueries in the next
186 * step, their INs are processed just before pulling them up.
188 parse->in_info_list = NIL;
189 if (parse->hasSubLinks)
190 parse->jointree->quals = pull_up_IN_clauses(parse,
191 parse->jointree->quals);
194 * Check to see if any subqueries in the rangetable can be merged into
197 parse->jointree = (FromExpr *)
198 pull_up_subqueries(parse, (Node *) parse->jointree, false);
201 * Detect whether any rangetable entries are RTE_JOIN kind; if not, we
202 * can avoid the expense of doing flatten_join_alias_vars(). Also
203 * check for outer joins --- if none, we can skip
204 * reduce_outer_joins(). This must be done after we have done
205 * pull_up_subqueries, of course.
207 parse->hasJoinRTEs = false;
208 hasOuterJoins = false;
209 foreach(lst, parse->rtable)
211 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lst);
213 if (rte->rtekind == RTE_JOIN)
215 parse->hasJoinRTEs = true;
216 if (IS_OUTER_JOIN(rte->jointype))
218 hasOuterJoins = true;
219 /* Can quit scanning once we find an outer join */
226 * Do expression preprocessing on targetlist and quals.
228 parse->targetList = (List *)
229 preprocess_expression(parse, (Node *) parse->targetList,
232 preprocess_qual_conditions(parse, (Node *) parse->jointree);
234 parse->havingQual = preprocess_expression(parse, parse->havingQual,
237 parse->limitOffset = preprocess_expression(parse, parse->limitOffset,
239 parse->limitCount = preprocess_expression(parse, parse->limitCount,
242 parse->in_info_list = (List *)
243 preprocess_expression(parse, (Node *) parse->in_info_list,
246 /* Also need to preprocess expressions for function RTEs */
247 foreach(lst, parse->rtable)
249 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lst);
251 if (rte->rtekind == RTE_FUNCTION)
252 rte->funcexpr = preprocess_expression(parse, rte->funcexpr,
257 * A HAVING clause without aggregates is equivalent to a WHERE clause
258 * (except it can only refer to grouped fields). Transfer any
259 * agg-free clauses of the HAVING qual into WHERE. This may seem like
260 * wasting cycles to cater to stupidly-written queries, but there are
261 * other reasons for doing it. Firstly, if the query contains no aggs
262 * at all, then we aren't going to generate an Agg plan node, and so
263 * there'll be no place to execute HAVING conditions; without this
264 * transfer, we'd lose the HAVING condition entirely, which is wrong.
265 * Secondly, when we push down a qual condition into a sub-query, it's
266 * easiest to push the qual into HAVING always, in case it contains
267 * aggs, and then let this code sort it out.
269 * Note that both havingQual and parse->jointree->quals are in
270 * implicitly-ANDed-list form at this point, even though they are
271 * declared as Node *.
274 foreach(lst, (List *) parse->havingQual)
276 Node *havingclause = (Node *) lfirst(lst);
278 if (contain_agg_clause(havingclause))
279 newHaving = lappend(newHaving, havingclause);
281 parse->jointree->quals = (Node *)
282 lappend((List *) parse->jointree->quals, havingclause);
284 parse->havingQual = (Node *) newHaving;
287 * If we have any outer joins, try to reduce them to plain inner
288 * joins. This step is most easily done after we've done expression
292 reduce_outer_joins(parse);
295 * See if we can simplify the jointree; opportunities for this may
296 * come from having pulled up subqueries, or from flattening explicit
297 * JOIN syntax. We must do this after flattening JOIN alias
298 * variables, since eliminating explicit JOIN nodes from the jointree
299 * will cause get_relids_for_join() to fail. But it should happen
300 * after reduce_outer_joins, anyway.
302 parse->jointree = (FromExpr *)
303 simplify_jointree(parse, (Node *) parse->jointree);
306 * Do the main planning. If we have an inherited target relation,
307 * that needs special processing, else go straight to
310 if (parse->resultRelation &&
311 (lst = expand_inherited_rtentry(parse, parse->resultRelation,
313 plan = inheritance_planner(parse, lst);
315 plan = grouping_planner(parse, tuple_fraction);
318 * If any subplans were generated, or if we're inside a subplan, build
319 * initPlan list and extParam/allParam sets for plan nodes.
321 if (PlannerPlanId != saved_planid || PlannerQueryLevel > 1)
323 Cost initplan_cost = 0;
325 /* Prepare extParam/allParam sets for all nodes in tree */
326 SS_finalize_plan(plan, parse->rtable);
329 * SS_finalize_plan doesn't handle initPlans, so we have to
330 * manually attach them to the topmost plan node, and add their
331 * extParams to the topmost node's, too.
333 * We also add the total_cost of each initPlan to the startup cost of
334 * the top node. This is a conservative overestimate, since in
335 * fact each initPlan might be executed later than plan startup,
336 * or even not at all.
338 plan->initPlan = PlannerInitPlan;
340 foreach(lst, plan->initPlan)
342 SubPlan *initplan = (SubPlan *) lfirst(lst);
344 plan->extParam = bms_add_members(plan->extParam,
345 initplan->plan->extParam);
346 initplan_cost += initplan->plan->total_cost;
349 plan->startup_cost += initplan_cost;
350 plan->total_cost += initplan_cost;
353 /* Return to outer subquery context */
355 PlannerInitPlan = saved_initplan;
356 /* we do NOT restore PlannerPlanId; that's not an oversight! */
362 * preprocess_expression
363 * Do subquery_planner's preprocessing work for an expression,
364 * which can be a targetlist, a WHERE clause (including JOIN/ON
365 * conditions), or a HAVING clause.
368 preprocess_expression(Query *parse, Node *expr, int kind)
371 * If the query has any join RTEs, replace join alias variables with
372 * base-relation variables. We must do this before sublink processing,
373 * else sublinks expanded out from join aliases wouldn't get
376 if (parse->hasJoinRTEs)
377 expr = flatten_join_alias_vars(parse, expr);
380 * If it's a qual or havingQual, canonicalize it. It seems most useful
381 * to do this before applying eval_const_expressions, since the latter
382 * can optimize flattened AND/ORs better than unflattened ones.
384 if (kind == EXPRKIND_QUAL)
386 expr = (Node *) canonicalize_qual((Expr *) expr);
388 #ifdef OPTIMIZER_DEBUG
389 printf("After canonicalize_qual()\n");
395 * Simplify constant expressions.
397 expr = eval_const_expressions(expr);
400 * If it's a qual or havingQual, convert it to implicit-AND format.
401 * (We don't want to do this before eval_const_expressions, since the
402 * latter would be unable to simplify a top-level AND correctly.)
404 if (kind == EXPRKIND_QUAL)
405 expr = (Node *) make_ands_implicit((Expr *) expr);
407 /* Expand SubLinks to SubPlans */
408 if (parse->hasSubLinks)
409 expr = SS_process_sublinks(expr, (kind == EXPRKIND_QUAL));
412 * XXX do not insert anything here unless you have grokked the
413 * comments in SS_replace_correlation_vars ...
416 /* Replace uplevel vars with Param nodes */
417 if (PlannerQueryLevel > 1)
418 expr = SS_replace_correlation_vars(expr);
424 * preprocess_qual_conditions
425 * Recursively scan the query's jointree and do subquery_planner's
426 * preprocessing work on each qual condition found therein.
429 preprocess_qual_conditions(Query *parse, Node *jtnode)
433 if (IsA(jtnode, RangeTblRef))
435 /* nothing to do here */
437 else if (IsA(jtnode, FromExpr))
439 FromExpr *f = (FromExpr *) jtnode;
442 foreach(l, f->fromlist)
443 preprocess_qual_conditions(parse, lfirst(l));
445 f->quals = preprocess_expression(parse, f->quals, EXPRKIND_QUAL);
447 else if (IsA(jtnode, JoinExpr))
449 JoinExpr *j = (JoinExpr *) jtnode;
451 preprocess_qual_conditions(parse, j->larg);
452 preprocess_qual_conditions(parse, j->rarg);
454 j->quals = preprocess_expression(parse, j->quals, EXPRKIND_QUAL);
457 elog(ERROR, "unrecognized node type: %d",
458 (int) nodeTag(jtnode));
461 /*--------------------
462 * inheritance_planner
463 * Generate a plan in the case where the result relation is an
466 * We have to handle this case differently from cases where a source
467 * relation is an inheritance set. Source inheritance is expanded at
468 * the bottom of the plan tree (see allpaths.c), but target inheritance
469 * has to be expanded at the top. The reason is that for UPDATE, each
470 * target relation needs a different targetlist matching its own column
471 * set. (This is not so critical for DELETE, but for simplicity we treat
472 * inherited DELETE the same way.) Fortunately, the UPDATE/DELETE target
473 * can never be the nullable side of an outer join, so it's OK to generate
476 * parse is the querytree produced by the parser & rewriter.
477 * inheritlist is an integer list of RT indexes for the result relation set.
479 * Returns a query plan.
480 *--------------------
483 inheritance_planner(Query *parse, List *inheritlist)
485 int parentRTindex = parse->resultRelation;
486 Oid parentOID = getrelid(parentRTindex, parse->rtable);
487 int mainrtlength = length(parse->rtable);
488 List *subplans = NIL;
492 foreach(l, inheritlist)
494 int childRTindex = lfirsti(l);
495 Oid childOID = getrelid(childRTindex, parse->rtable);
500 /* Generate modified query with this rel as target */
501 subquery = (Query *) adjust_inherited_attrs((Node *) parse,
502 parentRTindex, parentOID,
503 childRTindex, childOID);
505 subplan = grouping_planner(subquery, 0.0 /* retrieve all tuples */ );
506 subplans = lappend(subplans, subplan);
509 * It's possible that additional RTEs got added to the rangetable
510 * due to expansion of inherited source tables (see allpaths.c).
511 * If so, we must copy 'em back to the main parse tree's rtable.
513 * XXX my goodness this is ugly. Really need to think about ways to
514 * rein in planner's habit of scribbling on its input.
516 subrtlength = length(subquery->rtable);
517 if (subrtlength > mainrtlength)
519 List *subrt = subquery->rtable;
521 while (mainrtlength-- > 0) /* wish we had nthcdr() */
522 subrt = lnext(subrt);
523 parse->rtable = nconc(parse->rtable, subrt);
524 mainrtlength = subrtlength;
526 /* Save preprocessed tlist from first rel for use in Append */
528 tlist = subplan->targetlist;
531 /* Save the target-relations list for the executor, too */
532 parse->resultRelations = inheritlist;
534 /* Mark result as unordered (probably unnecessary) */
535 parse->query_pathkeys = NIL;
537 return (Plan *) make_append(subplans, true, tlist);
540 /*--------------------
542 * Perform planning steps related to grouping, aggregation, etc.
543 * This primarily means adding top-level processing to the basic
544 * query plan produced by query_planner.
546 * parse is the querytree produced by the parser & rewriter.
547 * tuple_fraction is the fraction of tuples we expect will be retrieved
549 * tuple_fraction is interpreted as follows:
550 * 0: expect all tuples to be retrieved (normal case)
551 * 0 < tuple_fraction < 1: expect the given fraction of tuples available
552 * from the plan to be retrieved
553 * tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
554 * expected to be retrieved (ie, a LIMIT specification)
556 * Returns a query plan. Also, parse->query_pathkeys is returned as the
557 * actual output ordering of the plan (in pathkey format).
558 *--------------------
561 grouping_planner(Query *parse, double tuple_fraction)
563 List *tlist = parse->targetList;
565 List *current_pathkeys;
568 if (parse->setOperations)
571 * Construct the plan for set operations. The result will not
572 * need any work except perhaps a top-level sort and/or LIMIT.
574 result_plan = plan_set_operations(parse);
577 * We should not need to call preprocess_targetlist, since we must
578 * be in a SELECT query node. Instead, use the targetlist
579 * returned by plan_set_operations (since this tells whether it
580 * returned any resjunk columns!), and transfer any sort key
581 * information from the original tlist.
583 Assert(parse->commandType == CMD_SELECT);
585 tlist = postprocess_setop_tlist(result_plan->targetlist, tlist);
588 * Can't handle FOR UPDATE here (parser should have checked
589 * already, but let's make sure).
593 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
594 errmsg("SELECT FOR UPDATE is not allowed with UNION/INTERSECT/EXCEPT")));
597 * We set current_pathkeys NIL indicating we do not know sort
598 * order. This is correct when the top set operation is UNION
599 * ALL, since the appended-together results are unsorted even if
600 * the subplans were sorted. For other set operations we could be
601 * smarter --- room for future improvement!
603 current_pathkeys = NIL;
606 * Calculate pathkeys that represent ordering requirements
608 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
610 sort_pathkeys = canonicalize_pathkeys(parse, sort_pathkeys);
614 /* No set operations, do regular planning */
616 List *group_pathkeys;
617 AttrNumber *groupColIdx = NULL;
618 bool need_tlist_eval = true;
620 double sub_tuple_fraction;
623 double dNumGroups = 0;
626 int numGroupCols = length(parse->groupClause);
627 bool use_hashed_grouping = false;
629 /* Preprocess targetlist in case we are inside an INSERT/UPDATE. */
630 tlist = preprocess_targetlist(tlist,
632 parse->resultRelation,
636 * Add TID targets for rels selected FOR UPDATE (should this be
637 * done in preprocess_targetlist?). The executor uses the TID to
638 * know which rows to lock, much as for UPDATE or DELETE.
645 * We've got trouble if the FOR UPDATE appears inside
646 * grouping, since grouping renders a reference to individual
647 * tuple CTIDs invalid. This is also checked at parse time,
648 * but that's insufficient because of rule substitution, query
651 CheckSelectForUpdate(parse);
654 * Currently the executor only supports FOR UPDATE at top
657 if (PlannerQueryLevel > 1)
659 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
660 errmsg("SELECT FOR UPDATE is not allowed in subqueries")));
662 foreach(l, parse->rowMarks)
664 Index rti = lfirsti(l);
670 resname = (char *) palloc(32);
671 snprintf(resname, 32, "ctid%u", rti);
672 resdom = makeResdom(length(tlist) + 1,
679 SelfItemPointerAttributeNumber,
684 ctid = makeTargetEntry(resdom, (Expr *) var);
685 tlist = lappend(tlist, ctid);
690 * Generate appropriate target list for subplan; may be different
691 * from tlist if grouping or aggregation is needed.
693 sub_tlist = make_subplanTargetList(parse, tlist,
694 &groupColIdx, &need_tlist_eval);
697 * Calculate pathkeys that represent grouping/ordering
700 group_pathkeys = make_pathkeys_for_sortclauses(parse->groupClause,
702 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
706 * Will need actual number of aggregates for estimating costs.
707 * Also, it's possible that optimization has eliminated all
708 * aggregates, and we may as well check for that here.
710 * Note: we do not attempt to detect duplicate aggregates here; a
711 * somewhat-overestimated count is okay for our present purposes.
715 numAggs = count_agg_clause((Node *) tlist) +
716 count_agg_clause(parse->havingQual);
718 parse->hasAggs = false;
722 * Figure out whether we need a sorted result from query_planner.
724 * If we have a GROUP BY clause, then we want a result sorted
725 * properly for grouping. Otherwise, if there is an ORDER BY
726 * clause, we want to sort by the ORDER BY clause. (Note: if we
727 * have both, and ORDER BY is a superset of GROUP BY, it would be
728 * tempting to request sort by ORDER BY --- but that might just
729 * leave us failing to exploit an available sort order at all.
730 * Needs more thought...)
732 if (parse->groupClause)
733 parse->query_pathkeys = group_pathkeys;
734 else if (parse->sortClause)
735 parse->query_pathkeys = sort_pathkeys;
737 parse->query_pathkeys = NIL;
740 * Adjust tuple_fraction if we see that we are going to apply
741 * limiting/grouping/aggregation/etc. This is not overridable by
742 * the caller, since it reflects plan actions that this routine
743 * will certainly take, not assumptions about context.
745 if (parse->limitCount != NULL)
748 * A LIMIT clause limits the absolute number of tuples
749 * returned. However, if it's not a constant LIMIT then we
750 * have to punt; for lack of a better idea, assume 10% of the
751 * plan's result is wanted.
753 double limit_fraction = 0.0;
755 if (IsA(parse->limitCount, Const))
757 Const *limitc = (Const *) parse->limitCount;
758 int32 count = DatumGetInt32(limitc->constvalue);
761 * A NULL-constant LIMIT represents "LIMIT ALL", which we
762 * treat the same as no limit (ie, expect to retrieve all
765 if (!limitc->constisnull && count > 0)
767 limit_fraction = (double) count;
768 /* We must also consider the OFFSET, if present */
769 if (parse->limitOffset != NULL)
771 if (IsA(parse->limitOffset, Const))
775 limitc = (Const *) parse->limitOffset;
776 offset = DatumGetInt32(limitc->constvalue);
777 if (!limitc->constisnull && offset > 0)
778 limit_fraction += (double) offset;
782 /* OFFSET is an expression ... punt ... */
783 limit_fraction = 0.10;
790 /* LIMIT is an expression ... punt ... */
791 limit_fraction = 0.10;
794 if (limit_fraction > 0.0)
797 * If we have absolute limits from both caller and LIMIT,
798 * use the smaller value; if one is fractional and the
799 * other absolute, treat the fraction as a fraction of the
800 * absolute value; else we can multiply the two fractions
803 if (tuple_fraction >= 1.0)
805 if (limit_fraction >= 1.0)
808 tuple_fraction = Min(tuple_fraction, limit_fraction);
812 /* caller absolute, limit fractional */
813 tuple_fraction *= limit_fraction;
814 if (tuple_fraction < 1.0)
815 tuple_fraction = 1.0;
818 else if (tuple_fraction > 0.0)
820 if (limit_fraction >= 1.0)
822 /* caller fractional, limit absolute */
823 tuple_fraction *= limit_fraction;
824 if (tuple_fraction < 1.0)
825 tuple_fraction = 1.0;
829 /* both fractional */
830 tuple_fraction *= limit_fraction;
835 /* no info from caller, just use limit */
836 tuple_fraction = limit_fraction;
842 * With grouping or aggregation, the tuple fraction to pass to
843 * query_planner() may be different from what it is at top level.
845 sub_tuple_fraction = tuple_fraction;
847 if (parse->groupClause)
850 * In GROUP BY mode, we have the little problem that we don't
851 * really know how many input tuples will be needed to make a
852 * group, so we can't translate an output LIMIT count into an
853 * input count. For lack of a better idea, assume 25% of the
854 * input data will be processed if there is any output limit.
855 * However, if the caller gave us a fraction rather than an
856 * absolute count, we can keep using that fraction (which
857 * amounts to assuming that all the groups are about the same
860 if (sub_tuple_fraction >= 1.0)
861 sub_tuple_fraction = 0.25;
864 * If both GROUP BY and ORDER BY are specified, we will need
865 * two levels of sort --- and, therefore, certainly need to
866 * read all the input tuples --- unless ORDER BY is a subset
867 * of GROUP BY. (We have not yet canonicalized the pathkeys,
868 * so must use the slower noncanonical comparison method.)
870 if (parse->groupClause && parse->sortClause &&
871 !noncanonical_pathkeys_contained_in(sort_pathkeys,
873 sub_tuple_fraction = 0.0;
875 else if (parse->hasAggs)
878 * Ungrouped aggregate will certainly want all the input
881 sub_tuple_fraction = 0.0;
883 else if (parse->distinctClause)
886 * SELECT DISTINCT, like GROUP, will absorb an unpredictable
887 * number of input tuples per output tuple. Handle the same
890 if (sub_tuple_fraction >= 1.0)
891 sub_tuple_fraction = 0.25;
895 * Generate the best unsorted and presorted paths for this Query
896 * (but note there may not be any presorted path).
898 query_planner(parse, sub_tlist, sub_tuple_fraction,
899 &cheapest_path, &sorted_path);
902 * We couldn't canonicalize group_pathkeys and sort_pathkeys
903 * before running query_planner(), so do it now.
905 group_pathkeys = canonicalize_pathkeys(parse, group_pathkeys);
906 sort_pathkeys = canonicalize_pathkeys(parse, sort_pathkeys);
909 * Consider whether we might want to use hashed grouping.
911 if (parse->groupClause)
914 double cheapest_path_rows;
915 int cheapest_path_width;
918 * Beware in this section of the possibility that
919 * cheapest_path->parent is NULL. This could happen if user
920 * does something silly like SELECT 'foo' GROUP BY 1;
922 if (cheapest_path->parent)
924 cheapest_path_rows = cheapest_path->parent->rows;
925 cheapest_path_width = cheapest_path->parent->width;
929 cheapest_path_rows = 1; /* assume non-set result */
930 cheapest_path_width = 100; /* arbitrary */
934 * Always estimate the number of groups. We can't do this
935 * until after running query_planner(), either.
937 groupExprs = get_sortgrouplist_exprs(parse->groupClause,
939 dNumGroups = estimate_num_groups(parse,
942 /* Also want it as a long int --- but 'ware overflow! */
943 numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
946 * Check can't-do-it conditions, including whether the
947 * grouping operators are hashjoinable.
949 * Executor doesn't support hashed aggregation with DISTINCT
950 * aggregates. (Doing so would imply storing *all* the input
951 * values in the hash table, which seems like a certain
954 if (!enable_hashagg || !hash_safe_grouping(parse))
955 use_hashed_grouping = false;
956 else if (parse->hasAggs &&
957 (contain_distinct_agg_clause((Node *) tlist) ||
958 contain_distinct_agg_clause(parse->havingQual)))
959 use_hashed_grouping = false;
963 * Use hashed grouping if (a) we think we can fit the
964 * hashtable into SortMem, *and* (b) the estimated cost is
965 * no more than doing it the other way. While avoiding
966 * the need for sorted input is usually a win, the fact
967 * that the output won't be sorted may be a loss; so we
968 * need to do an actual cost comparison.
970 * In most cases we have no good way to estimate the size of
971 * the transition value needed by an aggregate;
972 * arbitrarily assume it is 100 bytes. Also set the
973 * overhead per hashtable entry at 64 bytes.
975 int hashentrysize = cheapest_path_width + 64 + numAggs * 100;
977 if (hashentrysize * dNumGroups <= SortMem * 1024L)
980 * Okay, do the cost comparison. We need to consider
981 * cheapest_path + hashagg [+ final sort] versus
982 * either cheapest_path [+ sort] + group or agg [+
983 * final sort] or presorted_path + group or agg [+
984 * final sort] where brackets indicate a step that may
985 * not be needed. We assume query_planner() will have
986 * returned a presorted path only if it's a winner
987 * compared to cheapest_path for this purpose.
989 * These path variables are dummies that just hold cost
990 * fields; we don't make actual Paths for these steps.
995 cost_agg(&hashed_p, parse,
997 numGroupCols, dNumGroups,
998 cheapest_path->startup_cost,
999 cheapest_path->total_cost,
1000 cheapest_path_rows);
1001 /* Result of hashed agg is always unsorted */
1003 cost_sort(&hashed_p, parse, sort_pathkeys,
1004 hashed_p.total_cost,
1006 cheapest_path_width);
1010 sorted_p.startup_cost = sorted_path->startup_cost;
1011 sorted_p.total_cost = sorted_path->total_cost;
1012 current_pathkeys = sorted_path->pathkeys;
1016 sorted_p.startup_cost = cheapest_path->startup_cost;
1017 sorted_p.total_cost = cheapest_path->total_cost;
1018 current_pathkeys = cheapest_path->pathkeys;
1020 if (!pathkeys_contained_in(group_pathkeys,
1023 cost_sort(&sorted_p, parse, group_pathkeys,
1024 sorted_p.total_cost,
1026 cheapest_path_width);
1027 current_pathkeys = group_pathkeys;
1030 cost_agg(&sorted_p, parse,
1031 AGG_SORTED, numAggs,
1032 numGroupCols, dNumGroups,
1033 sorted_p.startup_cost,
1034 sorted_p.total_cost,
1035 cheapest_path_rows);
1037 cost_group(&sorted_p, parse,
1038 numGroupCols, dNumGroups,
1039 sorted_p.startup_cost,
1040 sorted_p.total_cost,
1041 cheapest_path_rows);
1042 /* The Agg or Group node will preserve ordering */
1043 if (sort_pathkeys &&
1044 !pathkeys_contained_in(sort_pathkeys,
1047 cost_sort(&sorted_p, parse, sort_pathkeys,
1048 sorted_p.total_cost,
1050 cheapest_path_width);
1054 * Now make the decision using the top-level tuple
1055 * fraction. First we have to convert an absolute
1056 * count (LIMIT) into fractional form.
1058 if (tuple_fraction >= 1.0)
1059 tuple_fraction /= dNumGroups;
1061 if (compare_fractional_path_costs(&hashed_p, &sorted_p,
1062 tuple_fraction) < 0)
1064 /* Hashed is cheaper, so use it */
1065 use_hashed_grouping = true;
1072 * Select the best path and create a plan to execute it.
1074 * If we are doing hashed grouping, we will always read all the input
1075 * tuples, so use the cheapest-total path. Otherwise, trust
1076 * query_planner's decision about which to use.
1078 if (sorted_path && !use_hashed_grouping)
1080 result_plan = create_plan(parse, sorted_path);
1081 current_pathkeys = sorted_path->pathkeys;
1085 result_plan = create_plan(parse, cheapest_path);
1086 current_pathkeys = cheapest_path->pathkeys;
1090 * create_plan() returns a plan with just a "flat" tlist of
1091 * required Vars. Usually we need to insert the sub_tlist as the
1092 * tlist of the top plan node. However, we can skip that if we
1093 * determined that whatever query_planner chose to return will be
1096 if (need_tlist_eval)
1099 * If the top-level plan node is one that cannot do expression
1100 * evaluation, we must insert a Result node to project the
1101 * desired tlist. Currently, the only plan node we might see
1102 * here that falls into that category is Append.
1104 if (IsA(result_plan, Append))
1106 result_plan = (Plan *) make_result(sub_tlist, NULL,
1112 * Otherwise, just replace the subplan's flat tlist with
1113 * the desired tlist.
1115 result_plan->targetlist = sub_tlist;
1119 * Also, account for the cost of evaluation of the sub_tlist.
1121 * Up to now, we have only been dealing with "flat" tlists,
1122 * containing just Vars. So their evaluation cost is zero
1123 * according to the model used by cost_qual_eval() (or if you
1124 * prefer, the cost is factored into cpu_tuple_cost). Thus we
1125 * can avoid accounting for tlist cost throughout
1126 * query_planner() and subroutines. But now we've inserted a
1127 * tlist that might contain actual operators, sub-selects, etc
1128 * --- so we'd better account for its cost.
1130 * Below this point, any tlist eval cost for added-on nodes
1131 * should be accounted for as we create those nodes.
1132 * Presently, of the node types we can add on, only Agg and
1133 * Group project new tlists (the rest just copy their input
1134 * tuples) --- so make_agg() and make_group() are responsible
1135 * for computing the added cost.
1137 cost_qual_eval(&tlist_cost, sub_tlist);
1138 result_plan->startup_cost += tlist_cost.startup;
1139 result_plan->total_cost += tlist_cost.startup +
1140 tlist_cost.per_tuple * result_plan->plan_rows;
1145 * Since we're using query_planner's tlist and not the one
1146 * make_subplanTargetList calculated, we have to refigure any
1147 * grouping-column indexes make_subplanTargetList computed.
1149 locate_grouping_columns(parse, tlist, result_plan->targetlist,
1154 * Insert AGG or GROUP node if needed, plus an explicit sort step
1157 * HAVING clause, if any, becomes qual of the Agg node
1159 if (use_hashed_grouping)
1161 /* Hashed aggregate plan --- no sort needed */
1162 result_plan = (Plan *) make_agg(parse,
1164 (List *) parse->havingQual,
1171 /* Hashed aggregation produces randomly-ordered results */
1172 current_pathkeys = NIL;
1174 else if (parse->hasAggs)
1176 /* Plain aggregate plan --- sort if needed */
1177 AggStrategy aggstrategy;
1179 if (parse->groupClause)
1181 if (!pathkeys_contained_in(group_pathkeys, current_pathkeys))
1183 result_plan = (Plan *)
1184 make_sort_from_groupcols(parse,
1188 current_pathkeys = group_pathkeys;
1190 aggstrategy = AGG_SORTED;
1193 * The AGG node will not change the sort ordering of its
1194 * groups, so current_pathkeys describes the result too.
1199 aggstrategy = AGG_PLAIN;
1200 /* Result will be only one row anyway; no sort order */
1201 current_pathkeys = NIL;
1204 result_plan = (Plan *) make_agg(parse,
1206 (List *) parse->havingQual,
1217 * If there are no Aggs, we shouldn't have any HAVING qual
1220 Assert(parse->havingQual == NULL);
1223 * If we have a GROUP BY clause, insert a group node (plus the
1224 * appropriate sort node, if necessary).
1226 if (parse->groupClause)
1229 * Add an explicit sort if we couldn't make the path come
1230 * out the way the GROUP node needs it.
1232 if (!pathkeys_contained_in(group_pathkeys, current_pathkeys))
1234 result_plan = (Plan *)
1235 make_sort_from_groupcols(parse,
1239 current_pathkeys = group_pathkeys;
1242 result_plan = (Plan *) make_group(parse,
1248 /* The Group node won't change sort ordering */
1251 } /* end of if (setOperations) */
1254 * If we were not able to make the plan come out in the right order,
1255 * add an explicit sort step.
1257 if (parse->sortClause)
1259 if (!pathkeys_contained_in(sort_pathkeys, current_pathkeys))
1261 result_plan = (Plan *)
1262 make_sort_from_sortclauses(parse,
1266 current_pathkeys = sort_pathkeys;
1271 * If there is a DISTINCT clause, add the UNIQUE node.
1273 if (parse->distinctClause)
1275 result_plan = (Plan *) make_unique(tlist, result_plan,
1276 parse->distinctClause);
1279 * If there was grouping or aggregation, leave plan_rows as-is
1280 * (ie, assume the result was already mostly unique). If not,
1281 * it's reasonable to assume the UNIQUE filter has effects
1282 * comparable to GROUP BY.
1284 if (!parse->groupClause && !parse->hasAggs)
1286 List *distinctExprs;
1288 distinctExprs = get_sortgrouplist_exprs(parse->distinctClause,
1290 result_plan->plan_rows = estimate_num_groups(parse,
1292 result_plan->plan_rows);
1297 * Finally, if there is a LIMIT/OFFSET clause, add the LIMIT node.
1299 if (parse->limitOffset || parse->limitCount)
1301 result_plan = (Plan *) make_limit(tlist, result_plan,
1307 * Return the actual output ordering in query_pathkeys for possible
1308 * use by an outer query level.
1310 parse->query_pathkeys = current_pathkeys;
1316 * hash_safe_grouping - are grouping operators hashable?
1318 * We assume hashed aggregation will work if the datatype's equality operator
1319 * is marked hashjoinable.
1322 hash_safe_grouping(Query *parse)
1326 foreach(gl, parse->groupClause)
1328 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1329 TargetEntry *tle = get_sortgroupclause_tle(grpcl, parse->targetList);
1333 optup = equality_oper(tle->resdom->restype, true);
1336 oprcanhash = ((Form_pg_operator) GETSTRUCT(optup))->oprcanhash;
1337 ReleaseSysCache(optup);
1345 * make_subplanTargetList
1346 * Generate appropriate target list when grouping is required.
1348 * When grouping_planner inserts Aggregate or Group plan nodes above
1349 * the result of query_planner, we typically want to pass a different
1350 * target list to query_planner than the outer plan nodes should have.
1351 * This routine generates the correct target list for the subplan.
1353 * The initial target list passed from the parser already contains entries
1354 * for all ORDER BY and GROUP BY expressions, but it will not have entries
1355 * for variables used only in HAVING clauses; so we need to add those
1356 * variables to the subplan target list. Also, if we are doing either
1357 * grouping or aggregation, we flatten all expressions except GROUP BY items
1358 * into their component variables; the other expressions will be computed by
1359 * the inserted nodes rather than by the subplan. For example,
1360 * given a query like
1361 * SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
1362 * we want to pass this targetlist to the subplan:
1364 * where the a+b target will be used by the Sort/Group steps, and the
1365 * other targets will be used for computing the final results. (In the
1366 * above example we could theoretically suppress the a and b targets and
1367 * pass down only c,d,a+b, but it's not really worth the trouble to
1368 * eliminate simple var references from the subplan. We will avoid doing
1369 * the extra computation to recompute a+b at the outer level; see
1370 * replace_vars_with_subplan_refs() in setrefs.c.)
1372 * If we are grouping or aggregating, *and* there are no non-Var grouping
1373 * expressions, then the returned tlist is effectively dummy; we do not
1374 * need to force it to be evaluated, because all the Vars it contains
1375 * should be present in the output of query_planner anyway.
1377 * 'parse' is the query being processed.
1378 * 'tlist' is the query's target list.
1379 * 'groupColIdx' receives an array of column numbers for the GROUP BY
1380 * expressions (if there are any) in the subplan's target list.
1381 * 'need_tlist_eval' is set true if we really need to evaluate the
1384 * The result is the targetlist to be passed to the subplan.
1388 make_subplanTargetList(Query *parse,
1390 AttrNumber **groupColIdx,
1391 bool *need_tlist_eval)
1397 *groupColIdx = NULL;
1400 * If we're not grouping or aggregating, nothing to do here;
1401 * query_planner should receive the unmodified target list.
1403 if (!parse->hasAggs && !parse->groupClause)
1405 *need_tlist_eval = true;
1410 * Otherwise, start with a "flattened" tlist (having just the vars
1411 * mentioned in the targetlist and HAVING qual --- but not upper-
1412 * level Vars; they will be replaced by Params later on).
1414 sub_tlist = flatten_tlist(tlist);
1415 extravars = pull_var_clause(parse->havingQual, false);
1416 sub_tlist = add_to_flat_tlist(sub_tlist, extravars);
1417 freeList(extravars);
1418 *need_tlist_eval = false; /* only eval if not flat tlist */
1421 * If grouping, create sub_tlist entries for all GROUP BY expressions
1422 * (GROUP BY items that are simple Vars should be in the list
1423 * already), and make an array showing where the group columns are in
1426 numCols = length(parse->groupClause);
1430 AttrNumber *grpColIdx;
1433 grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
1434 *groupColIdx = grpColIdx;
1436 foreach(gl, parse->groupClause)
1438 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1439 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1440 TargetEntry *te = NULL;
1443 /* Find or make a matching sub_tlist entry */
1444 foreach(sl, sub_tlist)
1446 te = (TargetEntry *) lfirst(sl);
1447 if (equal(groupexpr, te->expr))
1452 te = makeTargetEntry(makeResdom(length(sub_tlist) + 1,
1453 exprType(groupexpr),
1454 exprTypmod(groupexpr),
1457 (Expr *) groupexpr);
1458 sub_tlist = lappend(sub_tlist, te);
1459 *need_tlist_eval = true; /* it's not flat anymore */
1462 /* and save its resno */
1463 grpColIdx[keyno++] = te->resdom->resno;
1471 * locate_grouping_columns
1472 * Locate grouping columns in the tlist chosen by query_planner.
1474 * This is only needed if we don't use the sub_tlist chosen by
1475 * make_subplanTargetList. We have to forget the column indexes found
1476 * by that routine and re-locate the grouping vars in the real sub_tlist.
1479 locate_grouping_columns(Query *parse,
1482 AttrNumber *groupColIdx)
1488 * No work unless grouping.
1490 if (!parse->groupClause)
1492 Assert(groupColIdx == NULL);
1495 Assert(groupColIdx != NULL);
1497 foreach(gl, parse->groupClause)
1499 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1500 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1501 TargetEntry *te = NULL;
1504 foreach(sl, sub_tlist)
1506 te = (TargetEntry *) lfirst(sl);
1507 if (equal(groupexpr, te->expr))
1511 elog(ERROR, "failed to locate grouping columns");
1513 groupColIdx[keyno++] = te->resdom->resno;
1518 * postprocess_setop_tlist
1519 * Fix up targetlist returned by plan_set_operations().
1521 * We need to transpose sort key info from the orig_tlist into new_tlist.
1522 * NOTE: this would not be good enough if we supported resjunk sort keys
1523 * for results of set operations --- then, we'd need to project a whole
1524 * new tlist to evaluate the resjunk columns. For now, just ereport if we
1525 * find any resjunk columns in orig_tlist.
1528 postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
1532 foreach(l, new_tlist)
1534 TargetEntry *new_tle = (TargetEntry *) lfirst(l);
1535 TargetEntry *orig_tle;
1537 /* ignore resjunk columns in setop result */
1538 if (new_tle->resdom->resjunk)
1541 Assert(orig_tlist != NIL);
1542 orig_tle = (TargetEntry *) lfirst(orig_tlist);
1543 orig_tlist = lnext(orig_tlist);
1544 if (orig_tle->resdom->resjunk) /* should not happen */
1545 elog(ERROR, "resjunk output columns are not implemented");
1546 Assert(new_tle->resdom->resno == orig_tle->resdom->resno);
1547 Assert(new_tle->resdom->restype == orig_tle->resdom->restype);
1548 new_tle->resdom->ressortgroupref = orig_tle->resdom->ressortgroupref;
1550 if (orig_tlist != NIL)
1551 elog(ERROR, "resjunk output columns are not implemented");