1 /*-------------------------------------------------------------------------
4 * Routines to compute (and set) relation sizes and path costs
6 * Path costs are measured in arbitrary units established by these basic
9 * seq_page_cost Cost of a sequential page fetch
10 * random_page_cost Cost of a non-sequential page fetch
11 * cpu_tuple_cost Cost of typical CPU time to process a tuple
12 * cpu_index_tuple_cost Cost of typical CPU time to process an index tuple
13 * cpu_operator_cost Cost of CPU time to execute an operator or function
15 * We expect that the kernel will typically do some amount of read-ahead
16 * optimization; this in conjunction with seek costs means that seq_page_cost
17 * is normally considerably less than random_page_cost. (However, if the
18 * database is fully cached in RAM, it is reasonable to set them equal.)
20 * We also use a rough estimate "effective_cache_size" of the number of
21 * disk pages in Postgres + OS-level disk cache. (We can't simply use
22 * NBuffers for this purpose because that would ignore the effects of
23 * the kernel's disk cache.)
25 * Obviously, taking constants for these values is an oversimplification,
26 * but it's tough enough to get any useful estimates even at this level of
27 * detail. Note that all of these parameters are user-settable, in case
28 * the default values are drastically off for a particular platform.
30 * seq_page_cost and random_page_cost can also be overridden for an individual
31 * tablespace, in case some data is on a fast disk and other data is on a slow
32 * disk. Per-tablespace overrides never apply to temporary work files such as
33 * an external sort or a materialize node that overflows work_mem.
35 * We compute two separate costs for each path:
36 * total_cost: total estimated cost to fetch all tuples
37 * startup_cost: cost that is expended before first tuple is fetched
38 * In some scenarios, such as when there is a LIMIT or we are implementing
39 * an EXISTS(...) sub-select, it is not necessary to fetch all tuples of the
40 * path's result. A caller can estimate the cost of fetching a partial
41 * result by interpolating between startup_cost and total_cost. In detail:
42 * actual_cost = startup_cost +
43 * (total_cost - startup_cost) * tuples_to_fetch / path->parent->rows;
44 * Note that a base relation's rows count (and, by extension, plan_rows for
45 * plan nodes below the LIMIT node) are set without regard to any LIMIT, so
46 * that this equation works properly. (Also, these routines guarantee not to
47 * set the rows count to zero, so there will be no zero divide.) The LIMIT is
48 * applied as a top-level plan node.
50 * For largely historical reasons, most of the routines in this module use
51 * the passed result Path only to store their startup_cost and total_cost
52 * results into. All the input data they need is passed as separate
53 * parameters, even though much of it could be extracted from the Path.
54 * An exception is made for the cost_XXXjoin() routines, which expect all
55 * the non-cost fields of the passed XXXPath to be filled in.
58 * Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
59 * Portions Copyright (c) 1994, Regents of the University of California
62 * src/backend/optimizer/path/costsize.c
64 *-------------------------------------------------------------------------
71 #include "executor/executor.h"
72 #include "executor/nodeHash.h"
73 #include "miscadmin.h"
74 #include "nodes/nodeFuncs.h"
75 #include "optimizer/clauses.h"
76 #include "optimizer/cost.h"
77 #include "optimizer/pathnode.h"
78 #include "optimizer/placeholder.h"
79 #include "optimizer/plancat.h"
80 #include "optimizer/planmain.h"
81 #include "optimizer/restrictinfo.h"
82 #include "parser/parsetree.h"
83 #include "utils/lsyscache.h"
84 #include "utils/selfuncs.h"
85 #include "utils/spccache.h"
86 #include "utils/tuplesort.h"
89 #define LOG2(x) (log(x) / 0.693147180559945)
92 * Some Paths return less than the nominal number of rows of their parent
93 * relations; join nodes need to do this to get the correct input count:
95 #define PATH_ROWS(path) \
96 (IsA(path, UniquePath) ? \
97 ((UniquePath *) (path))->rows : \
101 double seq_page_cost = DEFAULT_SEQ_PAGE_COST;
102 double random_page_cost = DEFAULT_RANDOM_PAGE_COST;
103 double cpu_tuple_cost = DEFAULT_CPU_TUPLE_COST;
104 double cpu_index_tuple_cost = DEFAULT_CPU_INDEX_TUPLE_COST;
105 double cpu_operator_cost = DEFAULT_CPU_OPERATOR_COST;
107 int effective_cache_size = DEFAULT_EFFECTIVE_CACHE_SIZE;
109 Cost disable_cost = 1.0e10;
111 bool enable_seqscan = true;
112 bool enable_indexscan = true;
113 bool enable_bitmapscan = true;
114 bool enable_tidscan = true;
115 bool enable_sort = true;
116 bool enable_hashagg = true;
117 bool enable_nestloop = true;
118 bool enable_material = true;
119 bool enable_mergejoin = true;
120 bool enable_hashjoin = true;
126 } cost_qual_eval_context;
128 static MergeScanSelCache *cached_scansel(PlannerInfo *root,
131 static void cost_rescan(PlannerInfo *root, Path *path,
132 Cost *rescan_startup_cost, Cost *rescan_total_cost);
133 static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context);
134 static bool adjust_semi_join(PlannerInfo *root, JoinPath *path,
135 SpecialJoinInfo *sjinfo,
136 Selectivity *outer_match_frac,
137 Selectivity *match_count,
138 bool *indexed_join_quals);
139 static double approx_tuple_count(PlannerInfo *root, JoinPath *path,
141 static void set_rel_width(PlannerInfo *root, RelOptInfo *rel);
142 static double relation_byte_size(double tuples, int width);
143 static double page_size(double tuples, int width);
148 * Force a row-count estimate to a sane value.
151 clamp_row_est(double nrows)
154 * Force estimate to be at least one row, to make explain output look
155 * better and to avoid possible divide-by-zero when interpolating costs.
156 * Make it an integer, too.
169 * Determines and returns the cost of scanning a relation sequentially.
172 cost_seqscan(Path *path, PlannerInfo *root,
175 double spc_seq_page_cost;
176 Cost startup_cost = 0;
180 /* Should only be applied to base relations */
181 Assert(baserel->relid > 0);
182 Assert(baserel->rtekind == RTE_RELATION);
185 startup_cost += disable_cost;
187 /* fetch estimated page cost for tablespace containing table */
188 get_tablespace_page_costs(baserel->reltablespace,
195 run_cost += spc_seq_page_cost * baserel->pages;
198 startup_cost += baserel->baserestrictcost.startup;
199 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
200 run_cost += cpu_per_tuple * baserel->tuples;
202 path->startup_cost = startup_cost;
203 path->total_cost = startup_cost + run_cost;
208 * Determines and returns the cost of scanning a relation using an index.
210 * 'index' is the index to be used
211 * 'indexQuals' is the list of applicable qual clauses (implicit AND semantics)
212 * 'outer_rel' is the outer relation when we are considering using the index
213 * scan as the inside of a nestloop join (hence, some of the indexQuals
214 * are join clauses, and we should expect repeated scans of the index);
215 * NULL for a plain index scan
217 * cost_index() takes an IndexPath not just a Path, because it sets a few
218 * additional fields of the IndexPath besides startup_cost and total_cost.
219 * These fields are needed if the IndexPath is used in a BitmapIndexScan.
221 * NOTE: 'indexQuals' must contain only clauses usable as index restrictions.
222 * Any additional quals evaluated as qpquals may reduce the number of returned
223 * tuples, but they won't reduce the number of tuples we have to fetch from
224 * the table, so they don't reduce the scan cost.
226 * NOTE: as of 8.0, indexQuals is a list of RestrictInfo nodes, where formerly
227 * it was a list of bare clause expressions.
230 cost_index(IndexPath *path, PlannerInfo *root,
233 RelOptInfo *outer_rel)
235 RelOptInfo *baserel = index->rel;
236 Cost startup_cost = 0;
238 Cost indexStartupCost;
240 Selectivity indexSelectivity;
241 double indexCorrelation,
243 double spc_seq_page_cost,
244 spc_random_page_cost;
248 double tuples_fetched;
249 double pages_fetched;
251 /* Should only be applied to base relations */
252 Assert(IsA(baserel, RelOptInfo) &&
253 IsA(index, IndexOptInfo));
254 Assert(baserel->relid > 0);
255 Assert(baserel->rtekind == RTE_RELATION);
257 if (!enable_indexscan)
258 startup_cost += disable_cost;
261 * Call index-access-method-specific code to estimate the processing cost
262 * for scanning the index, as well as the selectivity of the index (ie,
263 * the fraction of main-table tuples we will have to retrieve) and its
264 * correlation to the main-table tuple order.
266 OidFunctionCall8(index->amcostestimate,
267 PointerGetDatum(root),
268 PointerGetDatum(index),
269 PointerGetDatum(indexQuals),
270 PointerGetDatum(outer_rel),
271 PointerGetDatum(&indexStartupCost),
272 PointerGetDatum(&indexTotalCost),
273 PointerGetDatum(&indexSelectivity),
274 PointerGetDatum(&indexCorrelation));
277 * Save amcostestimate's results for possible use in bitmap scan planning.
278 * We don't bother to save indexStartupCost or indexCorrelation, because a
279 * bitmap scan doesn't care about either.
281 path->indextotalcost = indexTotalCost;
282 path->indexselectivity = indexSelectivity;
284 /* all costs for touching index itself included here */
285 startup_cost += indexStartupCost;
286 run_cost += indexTotalCost - indexStartupCost;
288 /* estimate number of main-table tuples fetched */
289 tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
291 /* fetch estimated page costs for tablespace containing table */
292 get_tablespace_page_costs(baserel->reltablespace,
293 &spc_random_page_cost,
297 * Estimate number of main-table pages fetched, and compute I/O cost.
299 * When the index ordering is uncorrelated with the table ordering,
300 * we use an approximation proposed by Mackert and Lohman (see
301 * index_pages_fetched() for details) to compute the number of pages
302 * fetched, and then charge spc_random_page_cost per page fetched.
304 * When the index ordering is exactly correlated with the table ordering
305 * (just after a CLUSTER, for example), the number of pages fetched should
306 * be exactly selectivity * table_size. What's more, all but the first
307 * will be sequential fetches, not the random fetches that occur in the
308 * uncorrelated case. So if the number of pages is more than 1, we
310 * spc_random_page_cost + (pages_fetched - 1) * spc_seq_page_cost
311 * For partially-correlated indexes, we ought to charge somewhere between
312 * these two estimates. We currently interpolate linearly between the
313 * estimates based on the correlation squared (XXX is that appropriate?).
316 if (outer_rel != NULL && outer_rel->rows > 1)
319 * For repeated indexscans, the appropriate estimate for the
320 * uncorrelated case is to scale up the number of tuples fetched in
321 * the Mackert and Lohman formula by the number of scans, so that we
322 * estimate the number of pages fetched by all the scans; then
323 * pro-rate the costs for one scan. In this case we assume all the
324 * fetches are random accesses.
326 double num_scans = outer_rel->rows;
328 pages_fetched = index_pages_fetched(tuples_fetched * num_scans,
330 (double) index->pages,
333 max_IO_cost = (pages_fetched * spc_random_page_cost) / num_scans;
336 * In the perfectly correlated case, the number of pages touched by
337 * each scan is selectivity * table_size, and we can use the Mackert
338 * and Lohman formula at the page level to estimate how much work is
339 * saved by caching across scans. We still assume all the fetches are
340 * random, though, which is an overestimate that's hard to correct for
341 * without double-counting the cache effects. (But in most cases
342 * where such a plan is actually interesting, only one page would get
343 * fetched per scan anyway, so it shouldn't matter much.)
345 pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
347 pages_fetched = index_pages_fetched(pages_fetched * num_scans,
349 (double) index->pages,
352 min_IO_cost = (pages_fetched * spc_random_page_cost) / num_scans;
357 * Normal case: apply the Mackert and Lohman formula, and then
358 * interpolate between that and the correlation-derived result.
360 pages_fetched = index_pages_fetched(tuples_fetched,
362 (double) index->pages,
365 /* max_IO_cost is for the perfectly uncorrelated case (csquared=0) */
366 max_IO_cost = pages_fetched * spc_random_page_cost;
368 /* min_IO_cost is for the perfectly correlated case (csquared=1) */
369 pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
370 min_IO_cost = spc_random_page_cost;
371 if (pages_fetched > 1)
372 min_IO_cost += (pages_fetched - 1) * spc_seq_page_cost;
376 * Now interpolate based on estimated index order correlation to get total
377 * disk I/O cost for main table accesses.
379 csquared = indexCorrelation * indexCorrelation;
381 run_cost += max_IO_cost + csquared * (min_IO_cost - max_IO_cost);
384 * Estimate CPU costs per tuple.
386 * Normally the indexquals will be removed from the list of restriction
387 * clauses that we have to evaluate as qpquals, so we should subtract
388 * their costs from baserestrictcost. But if we are doing a join then
389 * some of the indexquals are join clauses and shouldn't be subtracted.
390 * Rather than work out exactly how much to subtract, we don't subtract
393 startup_cost += baserel->baserestrictcost.startup;
394 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
396 if (outer_rel == NULL)
398 QualCost index_qual_cost;
400 cost_qual_eval(&index_qual_cost, indexQuals, root);
401 /* any startup cost still has to be paid ... */
402 cpu_per_tuple -= index_qual_cost.per_tuple;
405 run_cost += cpu_per_tuple * tuples_fetched;
407 path->path.startup_cost = startup_cost;
408 path->path.total_cost = startup_cost + run_cost;
412 * index_pages_fetched
413 * Estimate the number of pages actually fetched after accounting for
416 * We use an approximation proposed by Mackert and Lohman, "Index Scans
417 * Using a Finite LRU Buffer: A Validated I/O Model", ACM Transactions
418 * on Database Systems, Vol. 14, No. 3, September 1989, Pages 401-424.
419 * The Mackert and Lohman approximation is that the number of pages
422 * min(2TNs/(2T+Ns), T) when T <= b
423 * 2TNs/(2T+Ns) when T > b and Ns <= 2Tb/(2T-b)
424 * b + (Ns - 2Tb/(2T-b))*(T-b)/T when T > b and Ns > 2Tb/(2T-b)
426 * T = # pages in table
427 * N = # tuples in table
428 * s = selectivity = fraction of table to be scanned
429 * b = # buffer pages available (we include kernel space here)
431 * We assume that effective_cache_size is the total number of buffer pages
432 * available for the whole query, and pro-rate that space across all the
433 * tables in the query and the index currently under consideration. (This
434 * ignores space needed for other indexes used by the query, but since we
435 * don't know which indexes will get used, we can't estimate that very well;
436 * and in any case counting all the tables may well be an overestimate, since
437 * depending on the join plan not all the tables may be scanned concurrently.)
439 * The product Ns is the number of tuples fetched; we pass in that
440 * product rather than calculating it here. "pages" is the number of pages
441 * in the object under consideration (either an index or a table).
442 * "index_pages" is the amount to add to the total table space, which was
443 * computed for us by query_planner.
445 * Caller is expected to have ensured that tuples_fetched is greater than zero
446 * and rounded to integer (see clamp_row_est). The result will likewise be
447 * greater than zero and integral.
450 index_pages_fetched(double tuples_fetched, BlockNumber pages,
451 double index_pages, PlannerInfo *root)
453 double pages_fetched;
458 /* T is # pages in table, but don't allow it to be zero */
459 T = (pages > 1) ? (double) pages : 1.0;
461 /* Compute number of pages assumed to be competing for cache space */
462 total_pages = root->total_table_pages + index_pages;
463 total_pages = Max(total_pages, 1.0);
464 Assert(T <= total_pages);
466 /* b is pro-rated share of effective_cache_size */
467 b = (double) effective_cache_size *T / total_pages;
469 /* force it positive and integral */
475 /* This part is the Mackert and Lohman formula */
479 (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
480 if (pages_fetched >= T)
483 pages_fetched = ceil(pages_fetched);
489 lim = (2.0 * T * b) / (2.0 * T - b);
490 if (tuples_fetched <= lim)
493 (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
498 b + (tuples_fetched - lim) * (T - b) / T;
500 pages_fetched = ceil(pages_fetched);
502 return pages_fetched;
506 * get_indexpath_pages
507 * Determine the total size of the indexes used in a bitmap index path.
509 * Note: if the same index is used more than once in a bitmap tree, we will
510 * count it multiple times, which perhaps is the wrong thing ... but it's
511 * not completely clear, and detecting duplicates is difficult, so ignore it
515 get_indexpath_pages(Path *bitmapqual)
520 if (IsA(bitmapqual, BitmapAndPath))
522 BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
524 foreach(l, apath->bitmapquals)
526 result += get_indexpath_pages((Path *) lfirst(l));
529 else if (IsA(bitmapqual, BitmapOrPath))
531 BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
533 foreach(l, opath->bitmapquals)
535 result += get_indexpath_pages((Path *) lfirst(l));
538 else if (IsA(bitmapqual, IndexPath))
540 IndexPath *ipath = (IndexPath *) bitmapqual;
542 result = (double) ipath->indexinfo->pages;
545 elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
551 * cost_bitmap_heap_scan
552 * Determines and returns the cost of scanning a relation using a bitmap
553 * index-then-heap plan.
555 * 'baserel' is the relation to be scanned
556 * 'bitmapqual' is a tree of IndexPaths, BitmapAndPaths, and BitmapOrPaths
557 * 'outer_rel' is the outer relation when we are considering using the bitmap
558 * scan as the inside of a nestloop join (hence, some of the indexQuals
559 * are join clauses, and we should expect repeated scans of the table);
560 * NULL for a plain bitmap scan
562 * Note: if this is a join inner path, the component IndexPaths in bitmapqual
563 * should have been costed accordingly.
566 cost_bitmap_heap_scan(Path *path, PlannerInfo *root, RelOptInfo *baserel,
567 Path *bitmapqual, RelOptInfo *outer_rel)
569 Cost startup_cost = 0;
572 Selectivity indexSelectivity;
575 double tuples_fetched;
576 double pages_fetched;
577 double spc_seq_page_cost,
578 spc_random_page_cost;
581 /* Should only be applied to base relations */
582 Assert(IsA(baserel, RelOptInfo));
583 Assert(baserel->relid > 0);
584 Assert(baserel->rtekind == RTE_RELATION);
586 if (!enable_bitmapscan)
587 startup_cost += disable_cost;
590 * Fetch total cost of obtaining the bitmap, as well as its total
593 cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
595 startup_cost += indexTotalCost;
597 /* Fetch estimated page costs for tablespace containing table. */
598 get_tablespace_page_costs(baserel->reltablespace,
599 &spc_random_page_cost,
603 * Estimate number of main-table pages fetched.
605 tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
607 T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
609 if (outer_rel != NULL && outer_rel->rows > 1)
612 * For repeated bitmap scans, scale up the number of tuples fetched in
613 * the Mackert and Lohman formula by the number of scans, so that we
614 * estimate the number of pages fetched by all the scans. Then
615 * pro-rate for one scan.
617 double num_scans = outer_rel->rows;
619 pages_fetched = index_pages_fetched(tuples_fetched * num_scans,
621 get_indexpath_pages(bitmapqual),
623 pages_fetched /= num_scans;
628 * For a single scan, the number of heap pages that need to be fetched
629 * is the same as the Mackert and Lohman formula for the case T <= b
630 * (ie, no re-reads needed).
632 pages_fetched = (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
634 if (pages_fetched >= T)
637 pages_fetched = ceil(pages_fetched);
640 * For small numbers of pages we should charge spc_random_page_cost
641 * apiece, while if nearly all the table's pages are being read, it's more
642 * appropriate to charge spc_seq_page_cost apiece. The effect is
643 * nonlinear, too. For lack of a better idea, interpolate like this to
644 * determine the cost per page.
646 if (pages_fetched >= 2.0)
647 cost_per_page = spc_random_page_cost -
648 (spc_random_page_cost - spc_seq_page_cost)
649 * sqrt(pages_fetched / T);
651 cost_per_page = spc_random_page_cost;
653 run_cost += pages_fetched * cost_per_page;
656 * Estimate CPU costs per tuple.
658 * Often the indexquals don't need to be rechecked at each tuple ... but
659 * not always, especially not if there are enough tuples involved that the
660 * bitmaps become lossy. For the moment, just assume they will be
663 startup_cost += baserel->baserestrictcost.startup;
664 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
666 run_cost += cpu_per_tuple * tuples_fetched;
668 path->startup_cost = startup_cost;
669 path->total_cost = startup_cost + run_cost;
673 * cost_bitmap_tree_node
674 * Extract cost and selectivity from a bitmap tree node (index/and/or)
677 cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
679 if (IsA(path, IndexPath))
681 *cost = ((IndexPath *) path)->indextotalcost;
682 *selec = ((IndexPath *) path)->indexselectivity;
685 * Charge a small amount per retrieved tuple to reflect the costs of
686 * manipulating the bitmap. This is mostly to make sure that a bitmap
687 * scan doesn't look to be the same cost as an indexscan to retrieve a
690 *cost += 0.1 * cpu_operator_cost * ((IndexPath *) path)->rows;
692 else if (IsA(path, BitmapAndPath))
694 *cost = path->total_cost;
695 *selec = ((BitmapAndPath *) path)->bitmapselectivity;
697 else if (IsA(path, BitmapOrPath))
699 *cost = path->total_cost;
700 *selec = ((BitmapOrPath *) path)->bitmapselectivity;
704 elog(ERROR, "unrecognized node type: %d", nodeTag(path));
705 *cost = *selec = 0; /* keep compiler quiet */
710 * cost_bitmap_and_node
711 * Estimate the cost of a BitmapAnd node
713 * Note that this considers only the costs of index scanning and bitmap
714 * creation, not the eventual heap access. In that sense the object isn't
715 * truly a Path, but it has enough path-like properties (costs in particular)
716 * to warrant treating it as one.
719 cost_bitmap_and_node(BitmapAndPath *path, PlannerInfo *root)
726 * We estimate AND selectivity on the assumption that the inputs are
727 * independent. This is probably often wrong, but we don't have the info
730 * The runtime cost of the BitmapAnd itself is estimated at 100x
731 * cpu_operator_cost for each tbm_intersect needed. Probably too small,
732 * definitely too simplistic?
736 foreach(l, path->bitmapquals)
738 Path *subpath = (Path *) lfirst(l);
740 Selectivity subselec;
742 cost_bitmap_tree_node(subpath, &subCost, &subselec);
746 totalCost += subCost;
747 if (l != list_head(path->bitmapquals))
748 totalCost += 100.0 * cpu_operator_cost;
750 path->bitmapselectivity = selec;
751 path->path.startup_cost = totalCost;
752 path->path.total_cost = totalCost;
756 * cost_bitmap_or_node
757 * Estimate the cost of a BitmapOr node
759 * See comments for cost_bitmap_and_node.
762 cost_bitmap_or_node(BitmapOrPath *path, PlannerInfo *root)
769 * We estimate OR selectivity on the assumption that the inputs are
770 * non-overlapping, since that's often the case in "x IN (list)" type
771 * situations. Of course, we clamp to 1.0 at the end.
773 * The runtime cost of the BitmapOr itself is estimated at 100x
774 * cpu_operator_cost for each tbm_union needed. Probably too small,
775 * definitely too simplistic? We are aware that the tbm_unions are
776 * optimized out when the inputs are BitmapIndexScans.
780 foreach(l, path->bitmapquals)
782 Path *subpath = (Path *) lfirst(l);
784 Selectivity subselec;
786 cost_bitmap_tree_node(subpath, &subCost, &subselec);
790 totalCost += subCost;
791 if (l != list_head(path->bitmapquals) &&
792 !IsA(subpath, IndexPath))
793 totalCost += 100.0 * cpu_operator_cost;
795 path->bitmapselectivity = Min(selec, 1.0);
796 path->path.startup_cost = totalCost;
797 path->path.total_cost = totalCost;
802 * Determines and returns the cost of scanning a relation using TIDs.
805 cost_tidscan(Path *path, PlannerInfo *root,
806 RelOptInfo *baserel, List *tidquals)
808 Cost startup_cost = 0;
810 bool isCurrentOf = false;
812 QualCost tid_qual_cost;
815 double spc_random_page_cost;
817 /* Should only be applied to base relations */
818 Assert(baserel->relid > 0);
819 Assert(baserel->rtekind == RTE_RELATION);
821 /* Count how many tuples we expect to retrieve */
825 if (IsA(lfirst(l), ScalarArrayOpExpr))
827 /* Each element of the array yields 1 tuple */
828 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) lfirst(l);
829 Node *arraynode = (Node *) lsecond(saop->args);
831 ntuples += estimate_array_length(arraynode);
833 else if (IsA(lfirst(l), CurrentOfExpr))
835 /* CURRENT OF yields 1 tuple */
841 /* It's just CTID = something, count 1 tuple */
847 * We must force TID scan for WHERE CURRENT OF, because only nodeTidscan.c
848 * understands how to do it correctly. Therefore, honor enable_tidscan
849 * only when CURRENT OF isn't present. Also note that cost_qual_eval
850 * counts a CurrentOfExpr as having startup cost disable_cost, which we
851 * subtract off here; that's to prevent other plan types such as seqscan
856 Assert(baserel->baserestrictcost.startup >= disable_cost);
857 startup_cost -= disable_cost;
859 else if (!enable_tidscan)
860 startup_cost += disable_cost;
863 * The TID qual expressions will be computed once, any other baserestrict
864 * quals once per retrived tuple.
866 cost_qual_eval(&tid_qual_cost, tidquals, root);
868 /* fetch estimated page cost for tablespace containing table */
869 get_tablespace_page_costs(baserel->reltablespace,
870 &spc_random_page_cost,
873 /* disk costs --- assume each tuple on a different page */
874 run_cost += spc_random_page_cost * ntuples;
877 startup_cost += baserel->baserestrictcost.startup +
878 tid_qual_cost.per_tuple;
879 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple -
880 tid_qual_cost.per_tuple;
881 run_cost += cpu_per_tuple * ntuples;
883 path->startup_cost = startup_cost;
884 path->total_cost = startup_cost + run_cost;
889 * Determines and returns the cost of scanning a subquery RTE.
892 cost_subqueryscan(Path *path, RelOptInfo *baserel)
898 /* Should only be applied to base relations that are subqueries */
899 Assert(baserel->relid > 0);
900 Assert(baserel->rtekind == RTE_SUBQUERY);
903 * Cost of path is cost of evaluating the subplan, plus cost of evaluating
904 * any restriction clauses that will be attached to the SubqueryScan node,
905 * plus cpu_tuple_cost to account for selection and projection overhead.
907 path->startup_cost = baserel->subplan->startup_cost;
908 path->total_cost = baserel->subplan->total_cost;
910 startup_cost = baserel->baserestrictcost.startup;
911 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
912 run_cost = cpu_per_tuple * baserel->tuples;
914 path->startup_cost += startup_cost;
915 path->total_cost += startup_cost + run_cost;
920 * Determines and returns the cost of scanning a function RTE.
923 cost_functionscan(Path *path, PlannerInfo *root, RelOptInfo *baserel)
925 Cost startup_cost = 0;
931 /* Should only be applied to base relations that are functions */
932 Assert(baserel->relid > 0);
933 rte = planner_rt_fetch(baserel->relid, root);
934 Assert(rte->rtekind == RTE_FUNCTION);
937 * Estimate costs of executing the function expression.
939 * Currently, nodeFunctionscan.c always executes the function to
940 * completion before returning any rows, and caches the results in a
941 * tuplestore. So the function eval cost is all startup cost, and per-row
944 * XXX in principle we ought to charge tuplestore spill costs if the
945 * number of rows is large. However, given how phony our rowcount
946 * estimates for functions tend to be, there's not a lot of point in that
947 * refinement right now.
949 cost_qual_eval_node(&exprcost, rte->funcexpr, root);
951 startup_cost += exprcost.startup + exprcost.per_tuple;
953 /* Add scanning CPU costs */
954 startup_cost += baserel->baserestrictcost.startup;
955 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
956 run_cost += cpu_per_tuple * baserel->tuples;
958 path->startup_cost = startup_cost;
959 path->total_cost = startup_cost + run_cost;
964 * Determines and returns the cost of scanning a VALUES RTE.
967 cost_valuesscan(Path *path, PlannerInfo *root, RelOptInfo *baserel)
969 Cost startup_cost = 0;
973 /* Should only be applied to base relations that are values lists */
974 Assert(baserel->relid > 0);
975 Assert(baserel->rtekind == RTE_VALUES);
978 * For now, estimate list evaluation cost at one operator eval per list
979 * (probably pretty bogus, but is it worth being smarter?)
981 cpu_per_tuple = cpu_operator_cost;
983 /* Add scanning CPU costs */
984 startup_cost += baserel->baserestrictcost.startup;
985 cpu_per_tuple += cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
986 run_cost += cpu_per_tuple * baserel->tuples;
988 path->startup_cost = startup_cost;
989 path->total_cost = startup_cost + run_cost;
994 * Determines and returns the cost of scanning a CTE RTE.
996 * Note: this is used for both self-reference and regular CTEs; the
997 * possible cost differences are below the threshold of what we could
998 * estimate accurately anyway. Note that the costs of evaluating the
999 * referenced CTE query are added into the final plan as initplan costs,
1000 * and should NOT be counted here.
1003 cost_ctescan(Path *path, PlannerInfo *root, RelOptInfo *baserel)
1005 Cost startup_cost = 0;
1009 /* Should only be applied to base relations that are CTEs */
1010 Assert(baserel->relid > 0);
1011 Assert(baserel->rtekind == RTE_CTE);
1013 /* Charge one CPU tuple cost per row for tuplestore manipulation */
1014 cpu_per_tuple = cpu_tuple_cost;
1016 /* Add scanning CPU costs */
1017 startup_cost += baserel->baserestrictcost.startup;
1018 cpu_per_tuple += cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
1019 run_cost += cpu_per_tuple * baserel->tuples;
1021 path->startup_cost = startup_cost;
1022 path->total_cost = startup_cost + run_cost;
1026 * cost_recursive_union
1027 * Determines and returns the cost of performing a recursive union,
1028 * and also the estimated output size.
1030 * We are given Plans for the nonrecursive and recursive terms.
1032 * Note that the arguments and output are Plans, not Paths as in most of
1033 * the rest of this module. That's because we don't bother setting up a
1034 * Path representation for recursive union --- we have only one way to do it.
1037 cost_recursive_union(Plan *runion, Plan *nrterm, Plan *rterm)
1043 /* We probably have decent estimates for the non-recursive term */
1044 startup_cost = nrterm->startup_cost;
1045 total_cost = nrterm->total_cost;
1046 total_rows = nrterm->plan_rows;
1049 * We arbitrarily assume that about 10 recursive iterations will be
1050 * needed, and that we've managed to get a good fix on the cost and output
1051 * size of each one of them. These are mighty shaky assumptions but it's
1052 * hard to see how to do better.
1054 total_cost += 10 * rterm->total_cost;
1055 total_rows += 10 * rterm->plan_rows;
1058 * Also charge cpu_tuple_cost per row to account for the costs of
1059 * manipulating the tuplestores. (We don't worry about possible
1060 * spill-to-disk costs.)
1062 total_cost += cpu_tuple_cost * total_rows;
1064 runion->startup_cost = startup_cost;
1065 runion->total_cost = total_cost;
1066 runion->plan_rows = total_rows;
1067 runion->plan_width = Max(nrterm->plan_width, rterm->plan_width);
1072 * Determines and returns the cost of sorting a relation, including
1073 * the cost of reading the input data.
1075 * If the total volume of data to sort is less than sort_mem, we will do
1076 * an in-memory sort, which requires no I/O and about t*log2(t) tuple
1077 * comparisons for t tuples.
1079 * If the total volume exceeds sort_mem, we switch to a tape-style merge
1080 * algorithm. There will still be about t*log2(t) tuple comparisons in
1081 * total, but we will also need to write and read each tuple once per
1082 * merge pass. We expect about ceil(logM(r)) merge passes where r is the
1083 * number of initial runs formed and M is the merge order used by tuplesort.c.
1084 * Since the average initial run should be about twice sort_mem, we have
1085 * disk traffic = 2 * relsize * ceil(logM(p / (2*sort_mem)))
1086 * cpu = comparison_cost * t * log2(t)
1088 * If the sort is bounded (i.e., only the first k result tuples are needed)
1089 * and k tuples can fit into sort_mem, we use a heap method that keeps only
1090 * k tuples in the heap; this will require about t*log2(k) tuple comparisons.
1092 * The disk traffic is assumed to be 3/4ths sequential and 1/4th random
1093 * accesses (XXX can't we refine that guess?)
1095 * By default, we charge two operator evals per tuple comparison, which should
1096 * be in the right ballpark in most cases. The caller can tweak this by
1097 * specifying nonzero comparison_cost; typically that's used for any extra
1098 * work that has to be done to prepare the inputs to the comparison operators.
1100 * 'pathkeys' is a list of sort keys
1101 * 'input_cost' is the total cost for reading the input data
1102 * 'tuples' is the number of tuples in the relation
1103 * 'width' is the average tuple width in bytes
1104 * 'comparison_cost' is the extra cost per comparison, if any
1105 * 'sort_mem' is the number of kilobytes of work memory allowed for the sort
1106 * 'limit_tuples' is the bound on the number of output tuples; -1 if no bound
1108 * NOTE: some callers currently pass NIL for pathkeys because they
1109 * can't conveniently supply the sort keys. Since this routine doesn't
1110 * currently do anything with pathkeys anyway, that doesn't matter...
1111 * but if it ever does, it should react gracefully to lack of key data.
1112 * (Actually, the thing we'd most likely be interested in is just the number
1113 * of sort keys, which all callers *could* supply.)
1116 cost_sort(Path *path, PlannerInfo *root,
1117 List *pathkeys, Cost input_cost, double tuples, int width,
1118 Cost comparison_cost, int sort_mem,
1119 double limit_tuples)
1121 Cost startup_cost = input_cost;
1123 double input_bytes = relation_byte_size(tuples, width);
1124 double output_bytes;
1125 double output_tuples;
1126 long sort_mem_bytes = sort_mem * 1024L;
1129 startup_cost += disable_cost;
1132 * We want to be sure the cost of a sort is never estimated as zero, even
1133 * if passed-in tuple count is zero. Besides, mustn't do log(0)...
1138 /* Include the default cost-per-comparison */
1139 comparison_cost += 2.0 * cpu_operator_cost;
1141 /* Do we have a useful LIMIT? */
1142 if (limit_tuples > 0 && limit_tuples < tuples)
1144 output_tuples = limit_tuples;
1145 output_bytes = relation_byte_size(output_tuples, width);
1149 output_tuples = tuples;
1150 output_bytes = input_bytes;
1153 if (output_bytes > sort_mem_bytes)
1156 * We'll have to use a disk-based sort of all the tuples
1158 double npages = ceil(input_bytes / BLCKSZ);
1159 double nruns = (input_bytes / sort_mem_bytes) * 0.5;
1160 double mergeorder = tuplesort_merge_order(sort_mem_bytes);
1162 double npageaccesses;
1167 * Assume about N log2 N comparisons
1169 startup_cost += comparison_cost * tuples * LOG2(tuples);
1173 /* Compute logM(r) as log(r) / log(M) */
1174 if (nruns > mergeorder)
1175 log_runs = ceil(log(nruns) / log(mergeorder));
1178 npageaccesses = 2.0 * npages * log_runs;
1179 /* Assume 3/4ths of accesses are sequential, 1/4th are not */
1180 startup_cost += npageaccesses *
1181 (seq_page_cost * 0.75 + random_page_cost * 0.25);
1183 else if (tuples > 2 * output_tuples || input_bytes > sort_mem_bytes)
1186 * We'll use a bounded heap-sort keeping just K tuples in memory, for
1187 * a total number of tuple comparisons of N log2 K; but the constant
1188 * factor is a bit higher than for quicksort. Tweak it so that the
1189 * cost curve is continuous at the crossover point.
1191 startup_cost += comparison_cost * tuples * LOG2(2.0 * output_tuples);
1195 /* We'll use plain quicksort on all the input tuples */
1196 startup_cost += comparison_cost * tuples * LOG2(tuples);
1200 * Also charge a small amount (arbitrarily set equal to operator cost) per
1201 * extracted tuple. We don't charge cpu_tuple_cost because a Sort node
1202 * doesn't do qual-checking or projection, so it has less overhead than
1203 * most plan nodes. Note it's correct to use tuples not output_tuples
1204 * here --- the upper LIMIT will pro-rate the run cost so we'd be double
1205 * counting the LIMIT otherwise.
1207 run_cost += cpu_operator_cost * tuples;
1209 path->startup_cost = startup_cost;
1210 path->total_cost = startup_cost + run_cost;
1215 * Determines and returns the cost of a MergeAppend node.
1217 * MergeAppend merges several pre-sorted input streams, using a heap that
1218 * at any given instant holds the next tuple from each stream. If there
1219 * are N streams, we need about N*log2(N) tuple comparisons to construct
1220 * the heap at startup, and then for each output tuple, about log2(N)
1221 * comparisons to delete the top heap entry and another log2(N) comparisons
1222 * to insert its successor from the same stream.
1224 * (The effective value of N will drop once some of the input streams are
1225 * exhausted, but it seems unlikely to be worth trying to account for that.)
1227 * The heap is never spilled to disk, since we assume N is not very large.
1228 * So this is much simpler than cost_sort.
1230 * As in cost_sort, we charge two operator evals per tuple comparison.
1232 * 'pathkeys' is a list of sort keys
1233 * 'n_streams' is the number of input streams
1234 * 'input_startup_cost' is the sum of the input streams' startup costs
1235 * 'input_total_cost' is the sum of the input streams' total costs
1236 * 'tuples' is the number of tuples in all the streams
1239 cost_merge_append(Path *path, PlannerInfo *root,
1240 List *pathkeys, int n_streams,
1241 Cost input_startup_cost, Cost input_total_cost,
1244 Cost startup_cost = 0;
1246 Cost comparison_cost;
1253 N = (n_streams < 2) ? 2.0 : (double) n_streams;
1256 /* Assumed cost per tuple comparison */
1257 comparison_cost = 2.0 * cpu_operator_cost;
1259 /* Heap creation cost */
1260 startup_cost += comparison_cost * N * logN;
1262 /* Per-tuple heap maintenance cost */
1263 run_cost += tuples * comparison_cost * 2.0 * logN;
1266 * Also charge a small amount (arbitrarily set equal to operator cost) per
1267 * extracted tuple. We don't charge cpu_tuple_cost because a MergeAppend
1268 * node doesn't do qual-checking or projection, so it has less overhead
1269 * than most plan nodes.
1271 run_cost += cpu_operator_cost * tuples;
1273 path->startup_cost = startup_cost + input_startup_cost;
1274 path->total_cost = startup_cost + run_cost + input_total_cost;
1279 * Determines and returns the cost of materializing a relation, including
1280 * the cost of reading the input data.
1282 * If the total volume of data to materialize exceeds work_mem, we will need
1283 * to write it to disk, so the cost is much higher in that case.
1285 * Note that here we are estimating the costs for the first scan of the
1286 * relation, so the materialization is all overhead --- any savings will
1287 * occur only on rescan, which is estimated in cost_rescan.
1290 cost_material(Path *path,
1291 Cost input_startup_cost, Cost input_total_cost,
1292 double tuples, int width)
1294 Cost startup_cost = input_startup_cost;
1295 Cost run_cost = input_total_cost - input_startup_cost;
1296 double nbytes = relation_byte_size(tuples, width);
1297 long work_mem_bytes = work_mem * 1024L;
1300 * Whether spilling or not, charge 2x cpu_operator_cost per tuple to
1301 * reflect bookkeeping overhead. (This rate must be more than what
1302 * cost_rescan charges for materialize, ie, cpu_operator_cost per tuple;
1303 * if it is exactly the same then there will be a cost tie between
1304 * nestloop with A outer, materialized B inner and nestloop with B outer,
1305 * materialized A inner. The extra cost ensures we'll prefer
1306 * materializing the smaller rel.) Note that this is normally a good deal
1307 * less than cpu_tuple_cost; which is OK because a Material plan node
1308 * doesn't do qual-checking or projection, so it's got less overhead than
1311 run_cost += 2 * cpu_operator_cost * tuples;
1314 * If we will spill to disk, charge at the rate of seq_page_cost per page.
1315 * This cost is assumed to be evenly spread through the plan run phase,
1316 * which isn't exactly accurate but our cost model doesn't allow for
1317 * nonuniform costs within the run phase.
1319 if (nbytes > work_mem_bytes)
1321 double npages = ceil(nbytes / BLCKSZ);
1323 run_cost += seq_page_cost * npages;
1326 path->startup_cost = startup_cost;
1327 path->total_cost = startup_cost + run_cost;
1332 * Determines and returns the cost of performing an Agg plan node,
1333 * including the cost of its input.
1335 * Note: when aggstrategy == AGG_SORTED, caller must ensure that input costs
1336 * are for appropriately-sorted input.
1339 cost_agg(Path *path, PlannerInfo *root,
1340 AggStrategy aggstrategy, int numAggs,
1341 int numGroupCols, double numGroups,
1342 Cost input_startup_cost, Cost input_total_cost,
1343 double input_tuples)
1349 * We charge one cpu_operator_cost per aggregate function per input tuple,
1350 * and another one per output tuple (corresponding to transfn and finalfn
1351 * calls respectively). If we are grouping, we charge an additional
1352 * cpu_operator_cost per grouping column per input tuple for grouping
1355 * We will produce a single output tuple if not grouping, and a tuple per
1356 * group otherwise. We charge cpu_tuple_cost for each output tuple.
1358 * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the
1359 * same total CPU cost, but AGG_SORTED has lower startup cost. If the
1360 * input path is already sorted appropriately, AGG_SORTED should be
1361 * preferred (since it has no risk of memory overflow). This will happen
1362 * as long as the computed total costs are indeed exactly equal --- but if
1363 * there's roundoff error we might do the wrong thing. So be sure that
1364 * the computations below form the same intermediate values in the same
1367 * Note: ideally we should use the pg_proc.procost costs of each
1368 * aggregate's component functions, but for now that seems like an
1369 * excessive amount of work.
1371 if (aggstrategy == AGG_PLAIN)
1373 startup_cost = input_total_cost;
1374 startup_cost += cpu_operator_cost * (input_tuples + 1) * numAggs;
1375 /* we aren't grouping */
1376 total_cost = startup_cost + cpu_tuple_cost;
1378 else if (aggstrategy == AGG_SORTED)
1380 /* Here we are able to deliver output on-the-fly */
1381 startup_cost = input_startup_cost;
1382 total_cost = input_total_cost;
1383 /* calcs phrased this way to match HASHED case, see note above */
1384 total_cost += cpu_operator_cost * input_tuples * numGroupCols;
1385 total_cost += cpu_operator_cost * input_tuples * numAggs;
1386 total_cost += cpu_operator_cost * numGroups * numAggs;
1387 total_cost += cpu_tuple_cost * numGroups;
1391 /* must be AGG_HASHED */
1392 startup_cost = input_total_cost;
1393 startup_cost += cpu_operator_cost * input_tuples * numGroupCols;
1394 startup_cost += cpu_operator_cost * input_tuples * numAggs;
1395 total_cost = startup_cost;
1396 total_cost += cpu_operator_cost * numGroups * numAggs;
1397 total_cost += cpu_tuple_cost * numGroups;
1400 path->startup_cost = startup_cost;
1401 path->total_cost = total_cost;
1406 * Determines and returns the cost of performing a WindowAgg plan node,
1407 * including the cost of its input.
1409 * Input is assumed already properly sorted.
1412 cost_windowagg(Path *path, PlannerInfo *root,
1413 int numWindowFuncs, int numPartCols, int numOrderCols,
1414 Cost input_startup_cost, Cost input_total_cost,
1415 double input_tuples)
1420 startup_cost = input_startup_cost;
1421 total_cost = input_total_cost;
1424 * We charge one cpu_operator_cost per window function per tuple (often a
1425 * drastic underestimate, but without a way to gauge how many tuples the
1426 * window function will fetch, it's hard to do better). We also charge
1427 * cpu_operator_cost per grouping column per tuple for grouping
1428 * comparisons, plus cpu_tuple_cost per tuple for general overhead.
1430 total_cost += cpu_operator_cost * input_tuples * numWindowFuncs;
1431 total_cost += cpu_operator_cost * input_tuples * (numPartCols + numOrderCols);
1432 total_cost += cpu_tuple_cost * input_tuples;
1434 path->startup_cost = startup_cost;
1435 path->total_cost = total_cost;
1440 * Determines and returns the cost of performing a Group plan node,
1441 * including the cost of its input.
1443 * Note: caller must ensure that input costs are for appropriately-sorted
1447 cost_group(Path *path, PlannerInfo *root,
1448 int numGroupCols, double numGroups,
1449 Cost input_startup_cost, Cost input_total_cost,
1450 double input_tuples)
1455 startup_cost = input_startup_cost;
1456 total_cost = input_total_cost;
1459 * Charge one cpu_operator_cost per comparison per input tuple. We assume
1460 * all columns get compared at most of the tuples.
1462 total_cost += cpu_operator_cost * input_tuples * numGroupCols;
1464 path->startup_cost = startup_cost;
1465 path->total_cost = total_cost;
1469 * If a nestloop's inner path is an indexscan, be sure to use its estimated
1470 * output row count, which may be lower than the restriction-clause-only row
1471 * count of its parent. (We don't include this case in the PATH_ROWS macro
1472 * because it applies *only* to a nestloop's inner relation.) We have to
1473 * be prepared to recurse through Append or MergeAppend nodes in case of an
1474 * appendrel. (It's not clear MergeAppend can be seen here, but we may as
1475 * well handle it if so.)
1478 nestloop_inner_path_rows(Path *path)
1482 if (IsA(path, IndexPath))
1483 result = ((IndexPath *) path)->rows;
1484 else if (IsA(path, BitmapHeapPath))
1485 result = ((BitmapHeapPath *) path)->rows;
1486 else if (IsA(path, AppendPath))
1491 foreach(l, ((AppendPath *) path)->subpaths)
1493 result += nestloop_inner_path_rows((Path *) lfirst(l));
1496 else if (IsA(path, MergeAppendPath))
1501 foreach(l, ((MergeAppendPath *) path)->subpaths)
1503 result += nestloop_inner_path_rows((Path *) lfirst(l));
1507 result = PATH_ROWS(path);
1514 * Determines and returns the cost of joining two relations using the
1515 * nested loop algorithm.
1517 * 'path' is already filled in except for the cost fields
1518 * 'sjinfo' is extra info about the join for selectivity estimation
1521 cost_nestloop(NestPath *path, PlannerInfo *root, SpecialJoinInfo *sjinfo)
1523 Path *outer_path = path->outerjoinpath;
1524 Path *inner_path = path->innerjoinpath;
1525 Cost startup_cost = 0;
1527 Cost inner_rescan_start_cost;
1528 Cost inner_rescan_total_cost;
1529 Cost inner_run_cost;
1530 Cost inner_rescan_run_cost;
1532 QualCost restrict_qual_cost;
1533 double outer_path_rows = PATH_ROWS(outer_path);
1534 double inner_path_rows = nestloop_inner_path_rows(inner_path);
1536 Selectivity outer_match_frac;
1537 Selectivity match_count;
1538 bool indexed_join_quals;
1540 if (!enable_nestloop)
1541 startup_cost += disable_cost;
1543 /* estimate costs to rescan the inner relation */
1544 cost_rescan(root, inner_path,
1545 &inner_rescan_start_cost,
1546 &inner_rescan_total_cost);
1548 /* cost of source data */
1551 * NOTE: clearly, we must pay both outer and inner paths' startup_cost
1552 * before we can start returning tuples, so the join's startup cost is
1553 * their sum. We'll also pay the inner path's rescan startup cost
1556 startup_cost += outer_path->startup_cost + inner_path->startup_cost;
1557 run_cost += outer_path->total_cost - outer_path->startup_cost;
1558 if (outer_path_rows > 1)
1559 run_cost += (outer_path_rows - 1) * inner_rescan_start_cost;
1561 inner_run_cost = inner_path->total_cost - inner_path->startup_cost;
1562 inner_rescan_run_cost = inner_rescan_total_cost - inner_rescan_start_cost;
1564 if (adjust_semi_join(root, path, sjinfo,
1567 &indexed_join_quals))
1569 double outer_matched_rows;
1570 Selectivity inner_scan_frac;
1573 * SEMI or ANTI join: executor will stop after first match.
1575 * For an outer-rel row that has at least one match, we can expect the
1576 * inner scan to stop after a fraction 1/(match_count+1) of the inner
1577 * rows, if the matches are evenly distributed. Since they probably
1578 * aren't quite evenly distributed, we apply a fuzz factor of 2.0 to
1579 * that fraction. (If we used a larger fuzz factor, we'd have to
1580 * clamp inner_scan_frac to at most 1.0; but since match_count is at
1581 * least 1, no such clamp is needed now.)
1583 * A complicating factor is that rescans may be cheaper than first
1584 * scans. If we never scan all the way to the end of the inner rel,
1585 * it might be (depending on the plan type) that we'd never pay the
1586 * whole inner first-scan run cost. However it is difficult to
1587 * estimate whether that will happen, so be conservative and always
1588 * charge the whole first-scan cost once.
1590 run_cost += inner_run_cost;
1592 outer_matched_rows = rint(outer_path_rows * outer_match_frac);
1593 inner_scan_frac = 2.0 / (match_count + 1.0);
1595 /* Add inner run cost for additional outer tuples having matches */
1596 if (outer_matched_rows > 1)
1597 run_cost += (outer_matched_rows - 1) * inner_rescan_run_cost * inner_scan_frac;
1599 /* Compute number of tuples processed (not number emitted!) */
1600 ntuples = outer_matched_rows * inner_path_rows * inner_scan_frac;
1603 * For unmatched outer-rel rows, there are two cases. If the inner
1604 * path is an indexscan using all the joinquals as indexquals, then an
1605 * unmatched row results in an indexscan returning no rows, which is
1606 * probably quite cheap. We estimate this case as the same cost to
1607 * return the first tuple of a nonempty scan. Otherwise, the executor
1608 * will have to scan the whole inner rel; not so cheap.
1610 if (indexed_join_quals)
1612 run_cost += (outer_path_rows - outer_matched_rows) *
1613 inner_rescan_run_cost / inner_path_rows;
1616 * We won't be evaluating any quals at all for these rows, so
1617 * don't add them to ntuples.
1622 run_cost += (outer_path_rows - outer_matched_rows) *
1623 inner_rescan_run_cost;
1624 ntuples += (outer_path_rows - outer_matched_rows) *
1630 /* Normal case; we'll scan whole input rel for each outer row */
1631 run_cost += inner_run_cost;
1632 if (outer_path_rows > 1)
1633 run_cost += (outer_path_rows - 1) * inner_rescan_run_cost;
1635 /* Compute number of tuples processed (not number emitted!) */
1636 ntuples = outer_path_rows * inner_path_rows;
1640 cost_qual_eval(&restrict_qual_cost, path->joinrestrictinfo, root);
1641 startup_cost += restrict_qual_cost.startup;
1642 cpu_per_tuple = cpu_tuple_cost + restrict_qual_cost.per_tuple;
1643 run_cost += cpu_per_tuple * ntuples;
1645 path->path.startup_cost = startup_cost;
1646 path->path.total_cost = startup_cost + run_cost;
1651 * Determines and returns the cost of joining two relations using the
1652 * merge join algorithm.
1654 * Unlike other costsize functions, this routine makes one actual decision:
1655 * whether we should materialize the inner path. We do that either because
1656 * the inner path can't support mark/restore, or because it's cheaper to
1657 * use an interposed Material node to handle mark/restore. When the decision
1658 * is cost-based it would be logically cleaner to build and cost two separate
1659 * paths with and without that flag set; but that would require repeating most
1660 * of the calculations here, which are not all that cheap. Since the choice
1661 * will not affect output pathkeys or startup cost, only total cost, there is
1662 * no possibility of wanting to keep both paths. So it seems best to make
1663 * the decision here and record it in the path's materialize_inner field.
1665 * 'path' is already filled in except for the cost fields and materialize_inner
1666 * 'sjinfo' is extra info about the join for selectivity estimation
1668 * Notes: path's mergeclauses should be a subset of the joinrestrictinfo list;
1669 * outersortkeys and innersortkeys are lists of the keys to be used
1670 * to sort the outer and inner relations, or NIL if no explicit
1671 * sort is needed because the source path is already ordered.
1674 cost_mergejoin(MergePath *path, PlannerInfo *root, SpecialJoinInfo *sjinfo)
1676 Path *outer_path = path->jpath.outerjoinpath;
1677 Path *inner_path = path->jpath.innerjoinpath;
1678 List *mergeclauses = path->path_mergeclauses;
1679 List *outersortkeys = path->outersortkeys;
1680 List *innersortkeys = path->innersortkeys;
1681 Cost startup_cost = 0;
1687 QualCost merge_qual_cost;
1688 QualCost qp_qual_cost;
1689 double outer_path_rows = PATH_ROWS(outer_path);
1690 double inner_path_rows = PATH_ROWS(inner_path);
1695 double mergejointuples,
1698 Selectivity outerstartsel,
1702 Path sort_path; /* dummy for result of cost_sort */
1704 /* Protect some assumptions below that rowcounts aren't zero */
1705 if (outer_path_rows <= 0)
1706 outer_path_rows = 1;
1707 if (inner_path_rows <= 0)
1708 inner_path_rows = 1;
1710 if (!enable_mergejoin)
1711 startup_cost += disable_cost;
1714 * Compute cost of the mergequals and qpquals (other restriction clauses)
1717 cost_qual_eval(&merge_qual_cost, mergeclauses, root);
1718 cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
1719 qp_qual_cost.startup -= merge_qual_cost.startup;
1720 qp_qual_cost.per_tuple -= merge_qual_cost.per_tuple;
1723 * Get approx # tuples passing the mergequals. We use approx_tuple_count
1724 * here because we need an estimate done with JOIN_INNER semantics.
1726 mergejointuples = approx_tuple_count(root, &path->jpath, mergeclauses);
1729 * When there are equal merge keys in the outer relation, the mergejoin
1730 * must rescan any matching tuples in the inner relation. This means
1731 * re-fetching inner tuples; we have to estimate how often that happens.
1733 * For regular inner and outer joins, the number of re-fetches can be
1734 * estimated approximately as size of merge join output minus size of
1735 * inner relation. Assume that the distinct key values are 1, 2, ..., and
1736 * denote the number of values of each key in the outer relation as m1,
1737 * m2, ...; in the inner relation, n1, n2, ... Then we have
1739 * size of join = m1 * n1 + m2 * n2 + ...
1741 * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... = m1 *
1742 * n1 + m2 * n2 + ... - (n1 + n2 + ...) = size of join - size of inner
1745 * This equation works correctly for outer tuples having no inner match
1746 * (nk = 0), but not for inner tuples having no outer match (mk = 0); we
1747 * are effectively subtracting those from the number of rescanned tuples,
1748 * when we should not. Can we do better without expensive selectivity
1751 * The whole issue is moot if we are working from a unique-ified outer
1754 if (IsA(outer_path, UniquePath))
1755 rescannedtuples = 0;
1758 rescannedtuples = mergejointuples - inner_path_rows;
1759 /* Must clamp because of possible underestimate */
1760 if (rescannedtuples < 0)
1761 rescannedtuples = 0;
1763 /* We'll inflate various costs this much to account for rescanning */
1764 rescanratio = 1.0 + (rescannedtuples / inner_path_rows);
1767 * A merge join will stop as soon as it exhausts either input stream
1768 * (unless it's an outer join, in which case the outer side has to be
1769 * scanned all the way anyway). Estimate fraction of the left and right
1770 * inputs that will actually need to be scanned. Likewise, we can
1771 * estimate the number of rows that will be skipped before the first join
1772 * pair is found, which should be factored into startup cost. We use only
1773 * the first (most significant) merge clause for this purpose. Since
1774 * mergejoinscansel() is a fairly expensive computation, we cache the
1775 * results in the merge clause RestrictInfo.
1777 if (mergeclauses && path->jpath.jointype != JOIN_FULL)
1779 RestrictInfo *firstclause = (RestrictInfo *) linitial(mergeclauses);
1784 MergeScanSelCache *cache;
1786 /* Get the input pathkeys to determine the sort-order details */
1787 opathkeys = outersortkeys ? outersortkeys : outer_path->pathkeys;
1788 ipathkeys = innersortkeys ? innersortkeys : inner_path->pathkeys;
1791 opathkey = (PathKey *) linitial(opathkeys);
1792 ipathkey = (PathKey *) linitial(ipathkeys);
1793 /* debugging check */
1794 if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
1795 opathkey->pk_strategy != ipathkey->pk_strategy ||
1796 opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
1797 elog(ERROR, "left and right pathkeys do not match in mergejoin");
1799 /* Get the selectivity with caching */
1800 cache = cached_scansel(root, firstclause, opathkey);
1802 if (bms_is_subset(firstclause->left_relids,
1803 outer_path->parent->relids))
1805 /* left side of clause is outer */
1806 outerstartsel = cache->leftstartsel;
1807 outerendsel = cache->leftendsel;
1808 innerstartsel = cache->rightstartsel;
1809 innerendsel = cache->rightendsel;
1813 /* left side of clause is inner */
1814 outerstartsel = cache->rightstartsel;
1815 outerendsel = cache->rightendsel;
1816 innerstartsel = cache->leftstartsel;
1817 innerendsel = cache->leftendsel;
1819 if (path->jpath.jointype == JOIN_LEFT ||
1820 path->jpath.jointype == JOIN_ANTI)
1822 outerstartsel = 0.0;
1825 else if (path->jpath.jointype == JOIN_RIGHT)
1827 innerstartsel = 0.0;
1833 /* cope with clauseless or full mergejoin */
1834 outerstartsel = innerstartsel = 0.0;
1835 outerendsel = innerendsel = 1.0;
1839 * Convert selectivities to row counts. We force outer_rows and
1840 * inner_rows to be at least 1, but the skip_rows estimates can be zero.
1842 outer_skip_rows = rint(outer_path_rows * outerstartsel);
1843 inner_skip_rows = rint(inner_path_rows * innerstartsel);
1844 outer_rows = clamp_row_est(outer_path_rows * outerendsel);
1845 inner_rows = clamp_row_est(inner_path_rows * innerendsel);
1847 Assert(outer_skip_rows <= outer_rows);
1848 Assert(inner_skip_rows <= inner_rows);
1851 * Readjust scan selectivities to account for above rounding. This is
1852 * normally an insignificant effect, but when there are only a few rows in
1853 * the inputs, failing to do this makes for a large percentage error.
1855 outerstartsel = outer_skip_rows / outer_path_rows;
1856 innerstartsel = inner_skip_rows / inner_path_rows;
1857 outerendsel = outer_rows / outer_path_rows;
1858 innerendsel = inner_rows / inner_path_rows;
1860 Assert(outerstartsel <= outerendsel);
1861 Assert(innerstartsel <= innerendsel);
1863 /* cost of source data */
1865 if (outersortkeys) /* do we need to sort outer? */
1867 cost_sort(&sort_path,
1870 outer_path->total_cost,
1872 outer_path->parent->width,
1876 startup_cost += sort_path.startup_cost;
1877 startup_cost += (sort_path.total_cost - sort_path.startup_cost)
1879 run_cost += (sort_path.total_cost - sort_path.startup_cost)
1880 * (outerendsel - outerstartsel);
1884 startup_cost += outer_path->startup_cost;
1885 startup_cost += (outer_path->total_cost - outer_path->startup_cost)
1887 run_cost += (outer_path->total_cost - outer_path->startup_cost)
1888 * (outerendsel - outerstartsel);
1891 if (innersortkeys) /* do we need to sort inner? */
1893 cost_sort(&sort_path,
1896 inner_path->total_cost,
1898 inner_path->parent->width,
1902 startup_cost += sort_path.startup_cost;
1903 startup_cost += (sort_path.total_cost - sort_path.startup_cost)
1905 inner_run_cost = (sort_path.total_cost - sort_path.startup_cost)
1906 * (innerendsel - innerstartsel);
1910 startup_cost += inner_path->startup_cost;
1911 startup_cost += (inner_path->total_cost - inner_path->startup_cost)
1913 inner_run_cost = (inner_path->total_cost - inner_path->startup_cost)
1914 * (innerendsel - innerstartsel);
1918 * Decide whether we want to materialize the inner input to shield it from
1919 * mark/restore and performing re-fetches. Our cost model for regular
1920 * re-fetches is that a re-fetch costs the same as an original fetch,
1921 * which is probably an overestimate; but on the other hand we ignore the
1922 * bookkeeping costs of mark/restore. Not clear if it's worth developing
1923 * a more refined model. So we just need to inflate the inner run cost by
1926 bare_inner_cost = inner_run_cost * rescanratio;
1929 * When we interpose a Material node the re-fetch cost is assumed to be
1930 * just cpu_operator_cost per tuple, independently of the underlying
1931 * plan's cost; and we charge an extra cpu_operator_cost per original
1932 * fetch as well. Note that we're assuming the materialize node will
1933 * never spill to disk, since it only has to remember tuples back to the
1934 * last mark. (If there are a huge number of duplicates, our other cost
1935 * factors will make the path so expensive that it probably won't get
1936 * chosen anyway.) So we don't use cost_rescan here.
1938 * Note: keep this estimate in sync with create_mergejoin_plan's labeling
1939 * of the generated Material node.
1941 mat_inner_cost = inner_run_cost +
1942 cpu_operator_cost * inner_path_rows * rescanratio;
1945 * Prefer materializing if it looks cheaper, unless the user has asked to
1946 * suppress materialization.
1948 if (enable_material && mat_inner_cost < bare_inner_cost)
1949 path->materialize_inner = true;
1952 * Even if materializing doesn't look cheaper, we *must* do it if the
1953 * inner path is to be used directly (without sorting) and it doesn't
1954 * support mark/restore.
1956 * Since the inner side must be ordered, and only Sorts and IndexScans can
1957 * create order to begin with, and they both support mark/restore, you
1958 * might think there's no problem --- but you'd be wrong. Nestloop and
1959 * merge joins can *preserve* the order of their inputs, so they can be
1960 * selected as the input of a mergejoin, and they don't support
1961 * mark/restore at present.
1963 * We don't test the value of enable_material here, because
1964 * materialization is required for correctness in this case, and turning
1965 * it off does not entitle us to deliver an invalid plan.
1967 else if (innersortkeys == NIL &&
1968 !ExecSupportsMarkRestore(inner_path->pathtype))
1969 path->materialize_inner = true;
1972 * Also, force materializing if the inner path is to be sorted and the
1973 * sort is expected to spill to disk. This is because the final merge
1974 * pass can be done on-the-fly if it doesn't have to support mark/restore.
1975 * We don't try to adjust the cost estimates for this consideration,
1978 * Since materialization is a performance optimization in this case,
1979 * rather than necessary for correctness, we skip it if enable_material is
1982 else if (enable_material && innersortkeys != NIL &&
1983 relation_byte_size(inner_path_rows, inner_path->parent->width) >
1985 path->materialize_inner = true;
1987 path->materialize_inner = false;
1989 /* Charge the right incremental cost for the chosen case */
1990 if (path->materialize_inner)
1991 run_cost += mat_inner_cost;
1993 run_cost += bare_inner_cost;
1998 * The number of tuple comparisons needed is approximately number of outer
1999 * rows plus number of inner rows plus number of rescanned tuples (can we
2000 * refine this?). At each one, we need to evaluate the mergejoin quals.
2002 startup_cost += merge_qual_cost.startup;
2003 startup_cost += merge_qual_cost.per_tuple *
2004 (outer_skip_rows + inner_skip_rows * rescanratio);
2005 run_cost += merge_qual_cost.per_tuple *
2006 ((outer_rows - outer_skip_rows) +
2007 (inner_rows - inner_skip_rows) * rescanratio);
2010 * For each tuple that gets through the mergejoin proper, we charge
2011 * cpu_tuple_cost plus the cost of evaluating additional restriction
2012 * clauses that are to be applied at the join. (This is pessimistic since
2013 * not all of the quals may get evaluated at each tuple.)
2015 * Note: we could adjust for SEMI/ANTI joins skipping some qual
2016 * evaluations here, but it's probably not worth the trouble.
2018 startup_cost += qp_qual_cost.startup;
2019 cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
2020 run_cost += cpu_per_tuple * mergejointuples;
2022 path->jpath.path.startup_cost = startup_cost;
2023 path->jpath.path.total_cost = startup_cost + run_cost;
2027 * run mergejoinscansel() with caching
2029 static MergeScanSelCache *
2030 cached_scansel(PlannerInfo *root, RestrictInfo *rinfo, PathKey *pathkey)
2032 MergeScanSelCache *cache;
2034 Selectivity leftstartsel,
2038 MemoryContext oldcontext;
2040 /* Do we have this result already? */
2041 foreach(lc, rinfo->scansel_cache)
2043 cache = (MergeScanSelCache *) lfirst(lc);
2044 if (cache->opfamily == pathkey->pk_opfamily &&
2045 cache->strategy == pathkey->pk_strategy &&
2046 cache->nulls_first == pathkey->pk_nulls_first)
2050 /* Nope, do the computation */
2051 mergejoinscansel(root,
2052 (Node *) rinfo->clause,
2053 pathkey->pk_opfamily,
2054 pathkey->pk_strategy,
2055 pathkey->pk_nulls_first,
2061 /* Cache the result in suitably long-lived workspace */
2062 oldcontext = MemoryContextSwitchTo(root->planner_cxt);
2064 cache = (MergeScanSelCache *) palloc(sizeof(MergeScanSelCache));
2065 cache->opfamily = pathkey->pk_opfamily;
2066 cache->strategy = pathkey->pk_strategy;
2067 cache->nulls_first = pathkey->pk_nulls_first;
2068 cache->leftstartsel = leftstartsel;
2069 cache->leftendsel = leftendsel;
2070 cache->rightstartsel = rightstartsel;
2071 cache->rightendsel = rightendsel;
2073 rinfo->scansel_cache = lappend(rinfo->scansel_cache, cache);
2075 MemoryContextSwitchTo(oldcontext);
2082 * Determines and returns the cost of joining two relations using the
2083 * hash join algorithm.
2085 * 'path' is already filled in except for the cost fields
2086 * 'sjinfo' is extra info about the join for selectivity estimation
2088 * Note: path's hashclauses should be a subset of the joinrestrictinfo list
2091 cost_hashjoin(HashPath *path, PlannerInfo *root, SpecialJoinInfo *sjinfo)
2093 Path *outer_path = path->jpath.outerjoinpath;
2094 Path *inner_path = path->jpath.innerjoinpath;
2095 List *hashclauses = path->path_hashclauses;
2096 Cost startup_cost = 0;
2099 QualCost hash_qual_cost;
2100 QualCost qp_qual_cost;
2101 double hashjointuples;
2102 double outer_path_rows = PATH_ROWS(outer_path);
2103 double inner_path_rows = PATH_ROWS(inner_path);
2104 int num_hashclauses = list_length(hashclauses);
2108 double virtualbuckets;
2109 Selectivity innerbucketsize;
2110 Selectivity outer_match_frac;
2111 Selectivity match_count;
2114 if (!enable_hashjoin)
2115 startup_cost += disable_cost;
2118 * Compute cost of the hashquals and qpquals (other restriction clauses)
2121 cost_qual_eval(&hash_qual_cost, hashclauses, root);
2122 cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
2123 qp_qual_cost.startup -= hash_qual_cost.startup;
2124 qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
2126 /* cost of source data */
2127 startup_cost += outer_path->startup_cost;
2128 run_cost += outer_path->total_cost - outer_path->startup_cost;
2129 startup_cost += inner_path->total_cost;
2132 * Cost of computing hash function: must do it once per input tuple. We
2133 * charge one cpu_operator_cost for each column's hash function. Also,
2134 * tack on one cpu_tuple_cost per inner row, to model the costs of
2135 * inserting the row into the hashtable.
2137 * XXX when a hashclause is more complex than a single operator, we really
2138 * should charge the extra eval costs of the left or right side, as
2139 * appropriate, here. This seems more work than it's worth at the moment.
2141 startup_cost += (cpu_operator_cost * num_hashclauses + cpu_tuple_cost)
2143 run_cost += cpu_operator_cost * num_hashclauses * outer_path_rows;
2146 * Get hash table size that executor would use for inner relation.
2148 * XXX for the moment, always assume that skew optimization will be
2149 * performed. As long as SKEW_WORK_MEM_PERCENT is small, it's not worth
2150 * trying to determine that for sure.
2152 * XXX at some point it might be interesting to try to account for skew
2153 * optimization in the cost estimate, but for now, we don't.
2155 ExecChooseHashTableSize(inner_path_rows,
2156 inner_path->parent->width,
2161 virtualbuckets = (double) numbuckets *(double) numbatches;
2163 /* mark the path with estimated # of batches */
2164 path->num_batches = numbatches;
2167 * Determine bucketsize fraction for inner relation. We use the smallest
2168 * bucketsize estimated for any individual hashclause; this is undoubtedly
2171 * BUT: if inner relation has been unique-ified, we can assume it's good
2172 * for hashing. This is important both because it's the right answer, and
2173 * because we avoid contaminating the cache with a value that's wrong for
2174 * non-unique-ified paths.
2176 if (IsA(inner_path, UniquePath))
2177 innerbucketsize = 1.0 / virtualbuckets;
2180 innerbucketsize = 1.0;
2181 foreach(hcl, hashclauses)
2183 RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(hcl);
2184 Selectivity thisbucketsize;
2186 Assert(IsA(restrictinfo, RestrictInfo));
2189 * First we have to figure out which side of the hashjoin clause
2190 * is the inner side.
2192 * Since we tend to visit the same clauses over and over when
2193 * planning a large query, we cache the bucketsize estimate in the
2194 * RestrictInfo node to avoid repeated lookups of statistics.
2196 if (bms_is_subset(restrictinfo->right_relids,
2197 inner_path->parent->relids))
2199 /* righthand side is inner */
2200 thisbucketsize = restrictinfo->right_bucketsize;
2201 if (thisbucketsize < 0)
2203 /* not cached yet */
2205 estimate_hash_bucketsize(root,
2206 get_rightop(restrictinfo->clause),
2208 restrictinfo->right_bucketsize = thisbucketsize;
2213 Assert(bms_is_subset(restrictinfo->left_relids,
2214 inner_path->parent->relids));
2215 /* lefthand side is inner */
2216 thisbucketsize = restrictinfo->left_bucketsize;
2217 if (thisbucketsize < 0)
2219 /* not cached yet */
2221 estimate_hash_bucketsize(root,
2222 get_leftop(restrictinfo->clause),
2224 restrictinfo->left_bucketsize = thisbucketsize;
2228 if (innerbucketsize > thisbucketsize)
2229 innerbucketsize = thisbucketsize;
2234 * If inner relation is too big then we will need to "batch" the join,
2235 * which implies writing and reading most of the tuples to disk an extra
2236 * time. Charge seq_page_cost per page, since the I/O should be nice and
2237 * sequential. Writing the inner rel counts as startup cost, all the rest
2242 double outerpages = page_size(outer_path_rows,
2243 outer_path->parent->width);
2244 double innerpages = page_size(inner_path_rows,
2245 inner_path->parent->width);
2247 startup_cost += seq_page_cost * innerpages;
2248 run_cost += seq_page_cost * (innerpages + 2 * outerpages);
2253 if (adjust_semi_join(root, &path->jpath, sjinfo,
2258 double outer_matched_rows;
2259 Selectivity inner_scan_frac;
2262 * SEMI or ANTI join: executor will stop after first match.
2264 * For an outer-rel row that has at least one match, we can expect the
2265 * bucket scan to stop after a fraction 1/(match_count+1) of the
2266 * bucket's rows, if the matches are evenly distributed. Since they
2267 * probably aren't quite evenly distributed, we apply a fuzz factor of
2268 * 2.0 to that fraction. (If we used a larger fuzz factor, we'd have
2269 * to clamp inner_scan_frac to at most 1.0; but since match_count is
2270 * at least 1, no such clamp is needed now.)
2272 outer_matched_rows = rint(outer_path_rows * outer_match_frac);
2273 inner_scan_frac = 2.0 / (match_count + 1.0);
2275 startup_cost += hash_qual_cost.startup;
2276 run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
2277 clamp_row_est(inner_path_rows * innerbucketsize * inner_scan_frac) * 0.5;
2280 * For unmatched outer-rel rows, the picture is quite a lot different.
2281 * In the first place, there is no reason to assume that these rows
2282 * preferentially hit heavily-populated buckets; instead assume they
2283 * are uncorrelated with the inner distribution and so they see an
2284 * average bucket size of inner_path_rows / virtualbuckets. In the
2285 * second place, it seems likely that they will have few if any exact
2286 * hash-code matches and so very few of the tuples in the bucket will
2287 * actually require eval of the hash quals. We don't have any good
2288 * way to estimate how many will, but for the moment assume that the
2289 * effective cost per bucket entry is one-tenth what it is for
2292 run_cost += hash_qual_cost.per_tuple *
2293 (outer_path_rows - outer_matched_rows) *
2294 clamp_row_est(inner_path_rows / virtualbuckets) * 0.05;
2296 /* Get # of tuples that will pass the basic join */
2297 if (path->jpath.jointype == JOIN_SEMI)
2298 hashjointuples = outer_matched_rows;
2300 hashjointuples = outer_path_rows - outer_matched_rows;
2305 * The number of tuple comparisons needed is the number of outer
2306 * tuples times the typical number of tuples in a hash bucket, which
2307 * is the inner relation size times its bucketsize fraction. At each
2308 * one, we need to evaluate the hashjoin quals. But actually,
2309 * charging the full qual eval cost at each tuple is pessimistic,
2310 * since we don't evaluate the quals unless the hash values match
2311 * exactly. For lack of a better idea, halve the cost estimate to
2314 startup_cost += hash_qual_cost.startup;
2315 run_cost += hash_qual_cost.per_tuple * outer_path_rows *
2316 clamp_row_est(inner_path_rows * innerbucketsize) * 0.5;
2319 * Get approx # tuples passing the hashquals. We use
2320 * approx_tuple_count here because we need an estimate done with
2321 * JOIN_INNER semantics.
2323 hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
2327 * For each tuple that gets through the hashjoin proper, we charge
2328 * cpu_tuple_cost plus the cost of evaluating additional restriction
2329 * clauses that are to be applied at the join. (This is pessimistic since
2330 * not all of the quals may get evaluated at each tuple.)
2332 startup_cost += qp_qual_cost.startup;
2333 cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
2334 run_cost += cpu_per_tuple * hashjointuples;
2336 path->jpath.path.startup_cost = startup_cost;
2337 path->jpath.path.total_cost = startup_cost + run_cost;
2343 * Figure the costs for a SubPlan (or initplan).
2345 * Note: we could dig the subplan's Plan out of the root list, but in practice
2346 * all callers have it handy already, so we make them pass it.
2349 cost_subplan(PlannerInfo *root, SubPlan *subplan, Plan *plan)
2353 /* Figure any cost for evaluating the testexpr */
2354 cost_qual_eval(&sp_cost,
2355 make_ands_implicit((Expr *) subplan->testexpr),
2358 if (subplan->useHashTable)
2361 * If we are using a hash table for the subquery outputs, then the
2362 * cost of evaluating the query is a one-time cost. We charge one
2363 * cpu_operator_cost per tuple for the work of loading the hashtable,
2366 sp_cost.startup += plan->total_cost +
2367 cpu_operator_cost * plan->plan_rows;
2370 * The per-tuple costs include the cost of evaluating the lefthand
2371 * expressions, plus the cost of probing the hashtable. We already
2372 * accounted for the lefthand expressions as part of the testexpr, and
2373 * will also have counted one cpu_operator_cost for each comparison
2374 * operator. That is probably too low for the probing cost, but it's
2375 * hard to make a better estimate, so live with it for now.
2381 * Otherwise we will be rescanning the subplan output on each
2382 * evaluation. We need to estimate how much of the output we will
2383 * actually need to scan. NOTE: this logic should agree with the
2384 * tuple_fraction estimates used by make_subplan() in
2387 Cost plan_run_cost = plan->total_cost - plan->startup_cost;
2389 if (subplan->subLinkType == EXISTS_SUBLINK)
2391 /* we only need to fetch 1 tuple */
2392 sp_cost.per_tuple += plan_run_cost / plan->plan_rows;
2394 else if (subplan->subLinkType == ALL_SUBLINK ||
2395 subplan->subLinkType == ANY_SUBLINK)
2397 /* assume we need 50% of the tuples */
2398 sp_cost.per_tuple += 0.50 * plan_run_cost;
2399 /* also charge a cpu_operator_cost per row examined */
2400 sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
2404 /* assume we need all tuples */
2405 sp_cost.per_tuple += plan_run_cost;
2409 * Also account for subplan's startup cost. If the subplan is
2410 * uncorrelated or undirect correlated, AND its topmost node is one
2411 * that materializes its output, assume that we'll only need to pay
2412 * its startup cost once; otherwise assume we pay the startup cost
2415 if (subplan->parParam == NIL &&
2416 ExecMaterializesOutput(nodeTag(plan)))
2417 sp_cost.startup += plan->startup_cost;
2419 sp_cost.per_tuple += plan->startup_cost;
2422 subplan->startup_cost = sp_cost.startup;
2423 subplan->per_call_cost = sp_cost.per_tuple;
2429 * Given a finished Path, estimate the costs of rescanning it after
2430 * having done so the first time. For some Path types a rescan is
2431 * cheaper than an original scan (if no parameters change), and this
2432 * function embodies knowledge about that. The default is to return
2433 * the same costs stored in the Path. (Note that the cost estimates
2434 * actually stored in Paths are always for first scans.)
2436 * This function is not currently intended to model effects such as rescans
2437 * being cheaper due to disk block caching; what we are concerned with is
2438 * plan types wherein the executor caches results explicitly, or doesn't
2439 * redo startup calculations, etc.
2442 cost_rescan(PlannerInfo *root, Path *path,
2443 Cost *rescan_startup_cost, /* output parameters */
2444 Cost *rescan_total_cost)
2446 switch (path->pathtype)
2448 case T_FunctionScan:
2451 * Currently, nodeFunctionscan.c always executes the function to
2452 * completion before returning any rows, and caches the results in
2453 * a tuplestore. So the function eval cost is all startup cost
2454 * and isn't paid over again on rescans. However, all run costs
2455 * will be paid over again.
2457 *rescan_startup_cost = 0;
2458 *rescan_total_cost = path->total_cost - path->startup_cost;
2463 * Assume that all of the startup cost represents hash table
2464 * building, which we won't have to do over.
2466 *rescan_startup_cost = 0;
2467 *rescan_total_cost = path->total_cost - path->startup_cost;
2470 case T_WorkTableScan:
2473 * These plan types materialize their final result in a
2474 * tuplestore or tuplesort object. So the rescan cost is only
2475 * cpu_tuple_cost per tuple, unless the result is large enough
2478 Cost run_cost = cpu_tuple_cost * path->parent->rows;
2479 double nbytes = relation_byte_size(path->parent->rows,
2480 path->parent->width);
2481 long work_mem_bytes = work_mem * 1024L;
2483 if (nbytes > work_mem_bytes)
2485 /* It will spill, so account for re-read cost */
2486 double npages = ceil(nbytes / BLCKSZ);
2488 run_cost += seq_page_cost * npages;
2490 *rescan_startup_cost = 0;
2491 *rescan_total_cost = run_cost;
2498 * These plan types not only materialize their results, but do
2499 * not implement qual filtering or projection. So they are
2500 * even cheaper to rescan than the ones above. We charge only
2501 * cpu_operator_cost per tuple. (Note: keep that in sync with
2502 * the run_cost charge in cost_sort, and also see comments in
2503 * cost_material before you change it.)
2505 Cost run_cost = cpu_operator_cost * path->parent->rows;
2506 double nbytes = relation_byte_size(path->parent->rows,
2507 path->parent->width);
2508 long work_mem_bytes = work_mem * 1024L;
2510 if (nbytes > work_mem_bytes)
2512 /* It will spill, so account for re-read cost */
2513 double npages = ceil(nbytes / BLCKSZ);
2515 run_cost += seq_page_cost * npages;
2517 *rescan_startup_cost = 0;
2518 *rescan_total_cost = run_cost;
2522 *rescan_startup_cost = path->startup_cost;
2523 *rescan_total_cost = path->total_cost;
2531 * Estimate the CPU costs of evaluating a WHERE clause.
2532 * The input can be either an implicitly-ANDed list of boolean
2533 * expressions, or a list of RestrictInfo nodes. (The latter is
2534 * preferred since it allows caching of the results.)
2535 * The result includes both a one-time (startup) component,
2536 * and a per-evaluation component.
2539 cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
2541 cost_qual_eval_context context;
2544 context.root = root;
2545 context.total.startup = 0;
2546 context.total.per_tuple = 0;
2548 /* We don't charge any cost for the implicit ANDing at top level ... */
2552 Node *qual = (Node *) lfirst(l);
2554 cost_qual_eval_walker(qual, &context);
2557 *cost = context.total;
2561 * cost_qual_eval_node
2562 * As above, for a single RestrictInfo or expression.
2565 cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
2567 cost_qual_eval_context context;
2569 context.root = root;
2570 context.total.startup = 0;
2571 context.total.per_tuple = 0;
2573 cost_qual_eval_walker(qual, &context);
2575 *cost = context.total;
2579 cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
2585 * RestrictInfo nodes contain an eval_cost field reserved for this
2586 * routine's use, so that it's not necessary to evaluate the qual clause's
2587 * cost more than once. If the clause's cost hasn't been computed yet,
2588 * the field's startup value will contain -1.
2590 if (IsA(node, RestrictInfo))
2592 RestrictInfo *rinfo = (RestrictInfo *) node;
2594 if (rinfo->eval_cost.startup < 0)
2596 cost_qual_eval_context locContext;
2598 locContext.root = context->root;
2599 locContext.total.startup = 0;
2600 locContext.total.per_tuple = 0;
2603 * For an OR clause, recurse into the marked-up tree so that we
2604 * set the eval_cost for contained RestrictInfos too.
2606 if (rinfo->orclause)
2607 cost_qual_eval_walker((Node *) rinfo->orclause, &locContext);
2609 cost_qual_eval_walker((Node *) rinfo->clause, &locContext);
2612 * If the RestrictInfo is marked pseudoconstant, it will be tested
2613 * only once, so treat its cost as all startup cost.
2615 if (rinfo->pseudoconstant)
2617 /* count one execution during startup */
2618 locContext.total.startup += locContext.total.per_tuple;
2619 locContext.total.per_tuple = 0;
2621 rinfo->eval_cost = locContext.total;
2623 context->total.startup += rinfo->eval_cost.startup;
2624 context->total.per_tuple += rinfo->eval_cost.per_tuple;
2625 /* do NOT recurse into children */
2630 * For each operator or function node in the given tree, we charge the
2631 * estimated execution cost given by pg_proc.procost (remember to multiply
2632 * this by cpu_operator_cost).
2634 * Vars and Consts are charged zero, and so are boolean operators (AND,
2635 * OR, NOT). Simplistic, but a lot better than no model at all.
2637 * Note that Aggref and WindowFunc nodes are (and should be) treated like
2638 * Vars --- whatever execution cost they have is absorbed into
2639 * plan-node-specific costing. As far as expression evaluation is
2640 * concerned they're just like Vars.
2642 * Should we try to account for the possibility of short-circuit
2643 * evaluation of AND/OR? Probably *not*, because that would make the
2644 * results depend on the clause ordering, and we are not in any position
2645 * to expect that the current ordering of the clauses is the one that's
2646 * going to end up being used. (Is it worth applying order_qual_clauses
2647 * much earlier in the planning process to fix this?)
2649 if (IsA(node, FuncExpr))
2651 context->total.per_tuple +=
2652 get_func_cost(((FuncExpr *) node)->funcid) * cpu_operator_cost;
2654 else if (IsA(node, OpExpr) ||
2655 IsA(node, DistinctExpr) ||
2656 IsA(node, NullIfExpr))
2658 /* rely on struct equivalence to treat these all alike */
2659 set_opfuncid((OpExpr *) node);
2660 context->total.per_tuple +=
2661 get_func_cost(((OpExpr *) node)->opfuncid) * cpu_operator_cost;
2663 else if (IsA(node, ScalarArrayOpExpr))
2666 * Estimate that the operator will be applied to about half of the
2667 * array elements before the answer is determined.
2669 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
2670 Node *arraynode = (Node *) lsecond(saop->args);
2672 set_sa_opfuncid(saop);
2673 context->total.per_tuple += get_func_cost(saop->opfuncid) *
2674 cpu_operator_cost * estimate_array_length(arraynode) * 0.5;
2676 else if (IsA(node, CoerceViaIO))
2678 CoerceViaIO *iocoerce = (CoerceViaIO *) node;
2683 /* check the result type's input function */
2684 getTypeInputInfo(iocoerce->resulttype,
2685 &iofunc, &typioparam);
2686 context->total.per_tuple += get_func_cost(iofunc) * cpu_operator_cost;
2687 /* check the input type's output function */
2688 getTypeOutputInfo(exprType((Node *) iocoerce->arg),
2689 &iofunc, &typisvarlena);
2690 context->total.per_tuple += get_func_cost(iofunc) * cpu_operator_cost;
2692 else if (IsA(node, ArrayCoerceExpr))
2694 ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
2695 Node *arraynode = (Node *) acoerce->arg;
2697 if (OidIsValid(acoerce->elemfuncid))
2698 context->total.per_tuple += get_func_cost(acoerce->elemfuncid) *
2699 cpu_operator_cost * estimate_array_length(arraynode);
2701 else if (IsA(node, RowCompareExpr))
2703 /* Conservatively assume we will check all the columns */
2704 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
2707 foreach(lc, rcexpr->opnos)
2709 Oid opid = lfirst_oid(lc);
2711 context->total.per_tuple += get_func_cost(get_opcode(opid)) *
2715 else if (IsA(node, CurrentOfExpr))
2717 /* Report high cost to prevent selection of anything but TID scan */
2718 context->total.startup += disable_cost;
2720 else if (IsA(node, SubLink))
2722 /* This routine should not be applied to un-planned expressions */
2723 elog(ERROR, "cannot handle unplanned sub-select");
2725 else if (IsA(node, SubPlan))
2728 * A subplan node in an expression typically indicates that the
2729 * subplan will be executed on each evaluation, so charge accordingly.
2730 * (Sub-selects that can be executed as InitPlans have already been
2731 * removed from the expression.)
2733 SubPlan *subplan = (SubPlan *) node;
2735 context->total.startup += subplan->startup_cost;
2736 context->total.per_tuple += subplan->per_call_cost;
2739 * We don't want to recurse into the testexpr, because it was already
2740 * counted in the SubPlan node's costs. So we're done.
2744 else if (IsA(node, AlternativeSubPlan))
2747 * Arbitrarily use the first alternative plan for costing. (We should
2748 * certainly only include one alternative, and we don't yet have
2749 * enough information to know which one the executor is most likely to
2752 AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
2754 return cost_qual_eval_walker((Node *) linitial(asplan->subplans),
2758 /* recurse into children */
2759 return expression_tree_walker(node, cost_qual_eval_walker,
2766 * Estimate how much of the inner input a SEMI or ANTI join
2767 * can be expected to scan.
2769 * In a hash or nestloop SEMI/ANTI join, the executor will stop scanning
2770 * inner rows as soon as it finds a match to the current outer row.
2771 * We should therefore adjust some of the cost components for this effect.
2772 * This function computes some estimates needed for these adjustments.
2774 * 'path' is already filled in except for the cost fields
2775 * 'sjinfo' is extra info about the join for selectivity estimation
2777 * Returns TRUE if this is a SEMI or ANTI join, FALSE if not.
2779 * Output parameters (set only in TRUE-result case):
2780 * *outer_match_frac is set to the fraction of the outer tuples that are
2781 * expected to have at least one match.
2782 * *match_count is set to the average number of matches expected for
2783 * outer tuples that have at least one match.
2784 * *indexed_join_quals is set to TRUE if all the joinquals are used as
2785 * inner index quals, FALSE if not.
2787 * indexed_join_quals can be passed as NULL if that information is not
2788 * relevant (it is only useful for the nestloop case).
2791 adjust_semi_join(PlannerInfo *root, JoinPath *path, SpecialJoinInfo *sjinfo,
2792 Selectivity *outer_match_frac,
2793 Selectivity *match_count,
2794 bool *indexed_join_quals)
2796 JoinType jointype = path->jointype;
2799 Selectivity avgmatch;
2800 SpecialJoinInfo norm_sjinfo;
2804 /* Fall out if it's not JOIN_SEMI or JOIN_ANTI */
2805 if (jointype != JOIN_SEMI && jointype != JOIN_ANTI)
2809 * Note: it's annoying to repeat this selectivity estimation on each call,
2810 * when the joinclause list will be the same for all path pairs
2811 * implementing a given join. clausesel.c will save us from the worst
2812 * effects of this by caching at the RestrictInfo level; but perhaps it'd
2813 * be worth finding a way to cache the results at a higher level.
2817 * In an ANTI join, we must ignore clauses that are "pushed down", since
2818 * those won't affect the match logic. In a SEMI join, we do not
2819 * distinguish joinquals from "pushed down" quals, so just use the whole
2820 * restrictinfo list.
2822 if (jointype == JOIN_ANTI)
2825 foreach(l, path->joinrestrictinfo)
2827 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
2829 Assert(IsA(rinfo, RestrictInfo));
2830 if (!rinfo->is_pushed_down)
2831 joinquals = lappend(joinquals, rinfo);
2835 joinquals = path->joinrestrictinfo;
2838 * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
2840 jselec = clauselist_selectivity(root,
2847 * Also get the normal inner-join selectivity of the join clauses.
2849 norm_sjinfo.type = T_SpecialJoinInfo;
2850 norm_sjinfo.min_lefthand = path->outerjoinpath->parent->relids;
2851 norm_sjinfo.min_righthand = path->innerjoinpath->parent->relids;
2852 norm_sjinfo.syn_lefthand = path->outerjoinpath->parent->relids;
2853 norm_sjinfo.syn_righthand = path->innerjoinpath->parent->relids;
2854 norm_sjinfo.jointype = JOIN_INNER;
2855 /* we don't bother trying to make the remaining fields valid */
2856 norm_sjinfo.lhs_strict = false;
2857 norm_sjinfo.delay_upper_joins = false;
2858 norm_sjinfo.join_quals = NIL;
2860 nselec = clauselist_selectivity(root,
2866 /* Avoid leaking a lot of ListCells */
2867 if (jointype == JOIN_ANTI)
2868 list_free(joinquals);
2871 * jselec can be interpreted as the fraction of outer-rel rows that have
2872 * any matches (this is true for both SEMI and ANTI cases). And nselec is
2873 * the fraction of the Cartesian product that matches. So, the average
2874 * number of matches for each outer-rel row that has at least one match is
2875 * nselec * inner_rows / jselec.
2877 * Note: it is correct to use the inner rel's "rows" count here, not
2878 * PATH_ROWS(), even if the inner path under consideration is an inner
2879 * indexscan. This is because we have included all the join clauses in
2880 * the selectivity estimate, even ones used in an inner indexscan.
2882 if (jselec > 0) /* protect against zero divide */
2884 avgmatch = nselec * path->innerjoinpath->parent->rows / jselec;
2885 /* Clamp to sane range */
2886 avgmatch = Max(1.0, avgmatch);
2891 *outer_match_frac = jselec;
2892 *match_count = avgmatch;
2895 * If requested, check whether the inner path uses all the joinquals as
2896 * indexquals. (If that's true, we can assume that an unmatched outer
2897 * tuple is cheap to process, whereas otherwise it's probably expensive.)
2899 if (indexed_join_quals)
2901 if (path->joinrestrictinfo != NIL)
2905 nrclauses = select_nonredundant_join_clauses(root,
2906 path->joinrestrictinfo,
2907 path->innerjoinpath);
2908 *indexed_join_quals = (nrclauses == NIL);
2912 /* a clauseless join does NOT qualify */
2913 *indexed_join_quals = false;
2922 * approx_tuple_count
2923 * Quick-and-dirty estimation of the number of join rows passing
2924 * a set of qual conditions.
2926 * The quals can be either an implicitly-ANDed list of boolean expressions,
2927 * or a list of RestrictInfo nodes (typically the latter).
2929 * We intentionally compute the selectivity under JOIN_INNER rules, even
2930 * if it's some type of outer join. This is appropriate because we are
2931 * trying to figure out how many tuples pass the initial merge or hash
2934 * This is quick-and-dirty because we bypass clauselist_selectivity, and
2935 * simply multiply the independent clause selectivities together. Now
2936 * clauselist_selectivity often can't do any better than that anyhow, but
2937 * for some situations (such as range constraints) it is smarter. However,
2938 * we can't effectively cache the results of clauselist_selectivity, whereas
2939 * the individual clause selectivities can be and are cached.
2941 * Since we are only using the results to estimate how many potential
2942 * output tuples are generated and passed through qpqual checking, it
2943 * seems OK to live with the approximation.
2946 approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
2949 double outer_tuples = path->outerjoinpath->parent->rows;
2950 double inner_tuples = path->innerjoinpath->parent->rows;
2951 SpecialJoinInfo sjinfo;
2952 Selectivity selec = 1.0;
2956 * Make up a SpecialJoinInfo for JOIN_INNER semantics.
2958 sjinfo.type = T_SpecialJoinInfo;
2959 sjinfo.min_lefthand = path->outerjoinpath->parent->relids;
2960 sjinfo.min_righthand = path->innerjoinpath->parent->relids;
2961 sjinfo.syn_lefthand = path->outerjoinpath->parent->relids;
2962 sjinfo.syn_righthand = path->innerjoinpath->parent->relids;
2963 sjinfo.jointype = JOIN_INNER;
2964 /* we don't bother trying to make the remaining fields valid */
2965 sjinfo.lhs_strict = false;
2966 sjinfo.delay_upper_joins = false;
2967 sjinfo.join_quals = NIL;
2969 /* Get the approximate selectivity */
2972 Node *qual = (Node *) lfirst(l);
2974 /* Note that clause_selectivity will be able to cache its result */
2975 selec *= clause_selectivity(root, qual, 0, JOIN_INNER, &sjinfo);
2978 /* Apply it to the input relation sizes */
2979 tuples = selec * outer_tuples * inner_tuples;
2981 return clamp_row_est(tuples);
2986 * set_baserel_size_estimates
2987 * Set the size estimates for the given base relation.
2989 * The rel's targetlist and restrictinfo list must have been constructed
2990 * already, and rel->tuples must be set.
2992 * We set the following fields of the rel node:
2993 * rows: the estimated number of output tuples (after applying
2994 * restriction clauses).
2995 * width: the estimated average output tuple width in bytes.
2996 * baserestrictcost: estimated cost of evaluating baserestrictinfo clauses.
2999 set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3003 /* Should only be applied to base relations */
3004 Assert(rel->relid > 0);
3006 nrows = rel->tuples *
3007 clauselist_selectivity(root,
3008 rel->baserestrictinfo,
3013 rel->rows = clamp_row_est(nrows);
3015 cost_qual_eval(&rel->baserestrictcost, rel->baserestrictinfo, root);
3017 set_rel_width(root, rel);
3021 * set_joinrel_size_estimates
3022 * Set the size estimates for the given join relation.
3024 * The rel's targetlist must have been constructed already, and a
3025 * restriction clause list that matches the given component rels must
3028 * Since there is more than one way to make a joinrel for more than two
3029 * base relations, the results we get here could depend on which component
3030 * rel pair is provided. In theory we should get the same answers no matter
3031 * which pair is provided; in practice, since the selectivity estimation
3032 * routines don't handle all cases equally well, we might not. But there's
3033 * not much to be done about it. (Would it make sense to repeat the
3034 * calculations for each pair of input rels that's encountered, and somehow
3035 * average the results? Probably way more trouble than it's worth.)
3037 * We set only the rows field here. The width field was already set by
3038 * build_joinrel_tlist, and baserestrictcost is not used for join rels.
3041 set_joinrel_size_estimates(PlannerInfo *root, RelOptInfo *rel,
3042 RelOptInfo *outer_rel,
3043 RelOptInfo *inner_rel,
3044 SpecialJoinInfo *sjinfo,
3047 JoinType jointype = sjinfo->jointype;
3053 * Compute joinclause selectivity. Note that we are only considering
3054 * clauses that become restriction clauses at this join level; we are not
3055 * double-counting them because they were not considered in estimating the
3056 * sizes of the component rels.
3058 * For an outer join, we have to distinguish the selectivity of the join's
3059 * own clauses (JOIN/ON conditions) from any clauses that were "pushed
3060 * down". For inner joins we just count them all as joinclauses.
3062 if (IS_OUTER_JOIN(jointype))
3064 List *joinquals = NIL;
3065 List *pushedquals = NIL;
3068 /* Grovel through the clauses to separate into two lists */
3069 foreach(l, restrictlist)
3071 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
3073 Assert(IsA(rinfo, RestrictInfo));
3074 if (rinfo->is_pushed_down)
3075 pushedquals = lappend(pushedquals, rinfo);
3077 joinquals = lappend(joinquals, rinfo);
3080 /* Get the separate selectivities */
3081 jselec = clauselist_selectivity(root,
3086 pselec = clauselist_selectivity(root,
3092 /* Avoid leaking a lot of ListCells */
3093 list_free(joinquals);
3094 list_free(pushedquals);
3098 jselec = clauselist_selectivity(root,
3103 pselec = 0.0; /* not used, keep compiler quiet */
3107 * Basically, we multiply size of Cartesian product by selectivity.
3109 * If we are doing an outer join, take that into account: the joinqual
3110 * selectivity has to be clamped using the knowledge that the output must
3111 * be at least as large as the non-nullable input. However, any
3112 * pushed-down quals are applied after the outer join, so their
3113 * selectivity applies fully.
3115 * For JOIN_SEMI and JOIN_ANTI, the selectivity is defined as the fraction
3116 * of LHS rows that have matches, and we apply that straightforwardly.
3121 nrows = outer_rel->rows * inner_rel->rows * jselec;
3124 nrows = outer_rel->rows * inner_rel->rows * jselec;
3125 if (nrows < outer_rel->rows)
3126 nrows = outer_rel->rows;
3130 nrows = outer_rel->rows * inner_rel->rows * jselec;
3131 if (nrows < outer_rel->rows)
3132 nrows = outer_rel->rows;
3133 if (nrows < inner_rel->rows)
3134 nrows = inner_rel->rows;
3138 nrows = outer_rel->rows * jselec;
3139 /* pselec not used */
3142 nrows = outer_rel->rows * (1.0 - jselec);
3146 /* other values not expected here */
3147 elog(ERROR, "unrecognized join type: %d", (int) jointype);
3148 nrows = 0; /* keep compiler quiet */
3152 rel->rows = clamp_row_est(nrows);
3156 * set_subquery_size_estimates
3157 * Set the size estimates for a base relation that is a subquery.
3159 * The rel's targetlist and restrictinfo list must have been constructed
3160 * already, and the plan for the subquery must have been completed.
3161 * We look at the subquery's plan and PlannerInfo to extract data.
3163 * We set the same fields as set_baserel_size_estimates.
3166 set_subquery_size_estimates(PlannerInfo *root, RelOptInfo *rel,
3167 PlannerInfo *subroot)
3172 /* Should only be applied to base relations that are subqueries */
3173 Assert(rel->relid > 0);
3174 rte = planner_rt_fetch(rel->relid, root);
3175 Assert(rte->rtekind == RTE_SUBQUERY);
3177 /* Copy raw number of output rows from subplan */
3178 rel->tuples = rel->subplan->plan_rows;
3181 * Compute per-output-column width estimates by examining the subquery's
3182 * targetlist. For any output that is a plain Var, get the width estimate
3183 * that was made while planning the subquery. Otherwise, fall back on a
3184 * datatype-based estimate.
3186 foreach(lc, subroot->parse->targetList)
3188 TargetEntry *te = (TargetEntry *) lfirst(lc);
3189 Node *texpr = (Node *) te->expr;
3192 Assert(IsA(te, TargetEntry));
3193 /* junk columns aren't visible to upper query */
3198 * XXX This currently doesn't work for subqueries containing set
3199 * operations, because the Vars in their tlists are bogus references
3200 * to the first leaf subquery, which wouldn't give the right answer
3201 * even if we could still get to its PlannerInfo. So fall back on
3202 * datatype in that case.
3204 if (IsA(texpr, Var) &&
3205 subroot->parse->setOperations == NULL)
3207 Var *var = (Var *) texpr;
3208 RelOptInfo *subrel = find_base_rel(subroot, var->varno);
3210 item_width = subrel->attr_widths[var->varattno - subrel->min_attr];
3214 item_width = get_typavgwidth(exprType(texpr), exprTypmod(texpr));
3216 Assert(item_width > 0);
3217 Assert(te->resno >= rel->min_attr && te->resno <= rel->max_attr);
3218 rel->attr_widths[te->resno - rel->min_attr] = item_width;
3221 /* Now estimate number of output rows, etc */
3222 set_baserel_size_estimates(root, rel);
3226 * set_function_size_estimates
3227 * Set the size estimates for a base relation that is a function call.
3229 * The rel's targetlist and restrictinfo list must have been constructed
3232 * We set the same fields as set_baserel_size_estimates.
3235 set_function_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3239 /* Should only be applied to base relations that are functions */
3240 Assert(rel->relid > 0);
3241 rte = planner_rt_fetch(rel->relid, root);
3242 Assert(rte->rtekind == RTE_FUNCTION);
3244 /* Estimate number of rows the function itself will return */
3245 rel->tuples = clamp_row_est(expression_returns_set_rows(rte->funcexpr));
3247 /* Now estimate number of output rows, etc */
3248 set_baserel_size_estimates(root, rel);
3252 * set_values_size_estimates
3253 * Set the size estimates for a base relation that is a values list.
3255 * The rel's targetlist and restrictinfo list must have been constructed
3258 * We set the same fields as set_baserel_size_estimates.
3261 set_values_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3265 /* Should only be applied to base relations that are values lists */
3266 Assert(rel->relid > 0);
3267 rte = planner_rt_fetch(rel->relid, root);
3268 Assert(rte->rtekind == RTE_VALUES);
3271 * Estimate number of rows the values list will return. We know this
3272 * precisely based on the list length (well, barring set-returning
3273 * functions in list items, but that's a refinement not catered for
3274 * anywhere else either).
3276 rel->tuples = list_length(rte->values_lists);
3278 /* Now estimate number of output rows, etc */
3279 set_baserel_size_estimates(root, rel);
3283 * set_cte_size_estimates
3284 * Set the size estimates for a base relation that is a CTE reference.
3286 * The rel's targetlist and restrictinfo list must have been constructed
3287 * already, and we need the completed plan for the CTE (if a regular CTE)
3288 * or the non-recursive term (if a self-reference).
3290 * We set the same fields as set_baserel_size_estimates.
3293 set_cte_size_estimates(PlannerInfo *root, RelOptInfo *rel, Plan *cteplan)
3297 /* Should only be applied to base relations that are CTE references */
3298 Assert(rel->relid > 0);
3299 rte = planner_rt_fetch(rel->relid, root);
3300 Assert(rte->rtekind == RTE_CTE);
3302 if (rte->self_reference)
3305 * In a self-reference, arbitrarily assume the average worktable size
3306 * is about 10 times the nonrecursive term's size.
3308 rel->tuples = 10 * cteplan->plan_rows;
3312 /* Otherwise just believe the CTE plan's output estimate */
3313 rel->tuples = cteplan->plan_rows;
3316 /* Now estimate number of output rows, etc */
3317 set_baserel_size_estimates(root, rel);
3323 * Set the estimated output width of a base relation.
3325 * The estimated output width is the sum of the per-attribute width estimates
3326 * for the actually-referenced columns, plus any PHVs or other expressions
3327 * that have to be calculated at this relation. This is the amount of data
3328 * we'd need to pass upwards in case of a sort, hash, etc.
3330 * NB: this works best on plain relations because it prefers to look at
3331 * real Vars. For subqueries, set_subquery_size_estimates will already have
3332 * copied up whatever per-column estimates were made within the subquery,
3333 * and for other types of rels there isn't much we can do anyway. We fall
3334 * back on (fairly stupid) datatype-based width estimates if we can't get
3335 * any better number.
3337 * The per-attribute width estimates are cached for possible re-use while
3338 * building join relations.
3341 set_rel_width(PlannerInfo *root, RelOptInfo *rel)
3343 Oid reloid = planner_rt_fetch(rel->relid, root)->relid;
3344 int32 tuple_width = 0;
3345 bool have_wholerow_var = false;
3348 foreach(lc, rel->reltargetlist)
3350 Node *node = (Node *) lfirst(lc);
3354 Var *var = (Var *) node;
3358 Assert(var->varno == rel->relid);
3359 Assert(var->varattno >= rel->min_attr);
3360 Assert(var->varattno <= rel->max_attr);
3362 ndx = var->varattno - rel->min_attr;
3365 * If it's a whole-row Var, we'll deal with it below after we
3366 * have already cached as many attr widths as possible.
3368 if (var->varattno == 0)
3370 have_wholerow_var = true;
3375 * The width may have been cached already (especially if it's
3376 * a subquery), so don't duplicate effort.
3378 if (rel->attr_widths[ndx] > 0)
3380 tuple_width += rel->attr_widths[ndx];
3384 /* Try to get column width from statistics */
3385 if (reloid != InvalidOid && var->varattno > 0)
3387 item_width = get_attavgwidth(reloid, var->varattno);
3390 rel->attr_widths[ndx] = item_width;
3391 tuple_width += item_width;
3397 * Not a plain relation, or can't find statistics for it. Estimate
3398 * using just the type info.
3400 item_width = get_typavgwidth(var->vartype, var->vartypmod);
3401 Assert(item_width > 0);
3402 rel->attr_widths[ndx] = item_width;
3403 tuple_width += item_width;
3405 else if (IsA(node, PlaceHolderVar))
3407 PlaceHolderVar *phv = (PlaceHolderVar *) node;
3408 PlaceHolderInfo *phinfo = find_placeholder_info(root, phv);
3410 tuple_width += phinfo->ph_width;
3415 * We could be looking at an expression pulled up from a subquery,
3416 * or a ROW() representing a whole-row child Var, etc. Do what we
3417 * can using the expression type information.
3421 item_width = get_typavgwidth(exprType(node), exprTypmod(node));
3422 Assert(item_width > 0);
3423 tuple_width += item_width;
3428 * If we have a whole-row reference, estimate its width as the sum of
3429 * per-column widths plus sizeof(HeapTupleHeaderData).
3431 if (have_wholerow_var)
3433 int32 wholerow_width = sizeof(HeapTupleHeaderData);
3435 if (reloid != InvalidOid)
3437 /* Real relation, so estimate true tuple width */
3438 wholerow_width += get_relation_data_width(reloid,
3439 rel->attr_widths - rel->min_attr);
3443 /* Do what we can with info for a phony rel */
3446 for (i = 1; i <= rel->max_attr; i++)
3447 wholerow_width += rel->attr_widths[i - rel->min_attr];
3450 rel->attr_widths[0 - rel->min_attr] = wholerow_width;
3453 * Include the whole-row Var as part of the output tuple. Yes,
3454 * that really is what happens at runtime.
3456 tuple_width += wholerow_width;
3459 Assert(tuple_width >= 0);
3460 rel->width = tuple_width;
3464 * relation_byte_size
3465 * Estimate the storage space in bytes for a given number of tuples
3466 * of a given width (size in bytes).
3469 relation_byte_size(double tuples, int width)
3471 return tuples * (MAXALIGN(width) + MAXALIGN(sizeof(HeapTupleHeaderData)));
3476 * Returns an estimate of the number of pages covered by a given
3477 * number of tuples of a given width (size in bytes).
3480 page_size(double tuples, int width)
3482 return ceil(relation_byte_size(tuples, width) / BLCKSZ);