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-2011, 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 * 'indexOrderBys' is the list of ORDER BY operators for amcanorderbyop indexes
213 * 'outer_rel' is the outer relation when we are considering using the index
214 * scan as the inside of a nestloop join (hence, some of the indexQuals
215 * are join clauses, and we should expect repeated scans of the index);
216 * NULL for a plain index scan
218 * cost_index() takes an IndexPath not just a Path, because it sets a few
219 * additional fields of the IndexPath besides startup_cost and total_cost.
220 * These fields are needed if the IndexPath is used in a BitmapIndexScan.
222 * indexQuals is a list of RestrictInfo nodes, but indexOrderBys is a list of
225 * NOTE: 'indexQuals' must contain only clauses usable as index restrictions.
226 * Any additional quals evaluated as qpquals may reduce the number of returned
227 * tuples, but they won't reduce the number of tuples we have to fetch from
228 * the table, so they don't reduce the scan cost.
231 cost_index(IndexPath *path, PlannerInfo *root,
235 RelOptInfo *outer_rel)
237 RelOptInfo *baserel = index->rel;
238 Cost startup_cost = 0;
240 Cost indexStartupCost;
242 Selectivity indexSelectivity;
243 double indexCorrelation,
245 double spc_seq_page_cost,
246 spc_random_page_cost;
250 double tuples_fetched;
251 double pages_fetched;
253 /* Should only be applied to base relations */
254 Assert(IsA(baserel, RelOptInfo) &&
255 IsA(index, IndexOptInfo));
256 Assert(baserel->relid > 0);
257 Assert(baserel->rtekind == RTE_RELATION);
259 if (!enable_indexscan)
260 startup_cost += disable_cost;
263 * Call index-access-method-specific code to estimate the processing cost
264 * for scanning the index, as well as the selectivity of the index (ie,
265 * the fraction of main-table tuples we will have to retrieve) and its
266 * correlation to the main-table tuple order.
268 OidFunctionCall9(index->amcostestimate,
269 PointerGetDatum(root),
270 PointerGetDatum(index),
271 PointerGetDatum(indexQuals),
272 PointerGetDatum(indexOrderBys),
273 PointerGetDatum(outer_rel),
274 PointerGetDatum(&indexStartupCost),
275 PointerGetDatum(&indexTotalCost),
276 PointerGetDatum(&indexSelectivity),
277 PointerGetDatum(&indexCorrelation));
280 * Save amcostestimate's results for possible use in bitmap scan planning.
281 * We don't bother to save indexStartupCost or indexCorrelation, because a
282 * bitmap scan doesn't care about either.
284 path->indextotalcost = indexTotalCost;
285 path->indexselectivity = indexSelectivity;
287 /* all costs for touching index itself included here */
288 startup_cost += indexStartupCost;
289 run_cost += indexTotalCost - indexStartupCost;
291 /* estimate number of main-table tuples fetched */
292 tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
294 /* fetch estimated page costs for tablespace containing table */
295 get_tablespace_page_costs(baserel->reltablespace,
296 &spc_random_page_cost,
300 * Estimate number of main-table pages fetched, and compute I/O cost.
302 * When the index ordering is uncorrelated with the table ordering,
303 * we use an approximation proposed by Mackert and Lohman (see
304 * index_pages_fetched() for details) to compute the number of pages
305 * fetched, and then charge spc_random_page_cost per page fetched.
307 * When the index ordering is exactly correlated with the table ordering
308 * (just after a CLUSTER, for example), the number of pages fetched should
309 * be exactly selectivity * table_size. What's more, all but the first
310 * will be sequential fetches, not the random fetches that occur in the
311 * uncorrelated case. So if the number of pages is more than 1, we
313 * spc_random_page_cost + (pages_fetched - 1) * spc_seq_page_cost
314 * For partially-correlated indexes, we ought to charge somewhere between
315 * these two estimates. We currently interpolate linearly between the
316 * estimates based on the correlation squared (XXX is that appropriate?).
319 if (outer_rel != NULL && outer_rel->rows > 1)
322 * For repeated indexscans, the appropriate estimate for the
323 * uncorrelated case is to scale up the number of tuples fetched in
324 * the Mackert and Lohman formula by the number of scans, so that we
325 * estimate the number of pages fetched by all the scans; then
326 * pro-rate the costs for one scan. In this case we assume all the
327 * fetches are random accesses.
329 double num_scans = outer_rel->rows;
331 pages_fetched = index_pages_fetched(tuples_fetched * num_scans,
333 (double) index->pages,
336 max_IO_cost = (pages_fetched * spc_random_page_cost) / num_scans;
339 * In the perfectly correlated case, the number of pages touched by
340 * each scan is selectivity * table_size, and we can use the Mackert
341 * and Lohman formula at the page level to estimate how much work is
342 * saved by caching across scans. We still assume all the fetches are
343 * random, though, which is an overestimate that's hard to correct for
344 * without double-counting the cache effects. (But in most cases
345 * where such a plan is actually interesting, only one page would get
346 * fetched per scan anyway, so it shouldn't matter much.)
348 pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
350 pages_fetched = index_pages_fetched(pages_fetched * num_scans,
352 (double) index->pages,
355 min_IO_cost = (pages_fetched * spc_random_page_cost) / num_scans;
360 * Normal case: apply the Mackert and Lohman formula, and then
361 * interpolate between that and the correlation-derived result.
363 pages_fetched = index_pages_fetched(tuples_fetched,
365 (double) index->pages,
368 /* max_IO_cost is for the perfectly uncorrelated case (csquared=0) */
369 max_IO_cost = pages_fetched * spc_random_page_cost;
371 /* min_IO_cost is for the perfectly correlated case (csquared=1) */
372 pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
373 min_IO_cost = spc_random_page_cost;
374 if (pages_fetched > 1)
375 min_IO_cost += (pages_fetched - 1) * spc_seq_page_cost;
379 * Now interpolate based on estimated index order correlation to get total
380 * disk I/O cost for main table accesses.
382 csquared = indexCorrelation * indexCorrelation;
384 run_cost += max_IO_cost + csquared * (min_IO_cost - max_IO_cost);
387 * Estimate CPU costs per tuple.
389 * Normally the indexquals will be removed from the list of restriction
390 * clauses that we have to evaluate as qpquals, so we should subtract
391 * their costs from baserestrictcost. But if we are doing a join then
392 * some of the indexquals are join clauses and shouldn't be subtracted.
393 * Rather than work out exactly how much to subtract, we don't subtract
396 startup_cost += baserel->baserestrictcost.startup;
397 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
399 if (outer_rel == NULL)
401 QualCost index_qual_cost;
403 cost_qual_eval(&index_qual_cost, indexQuals, root);
404 /* any startup cost still has to be paid ... */
405 cpu_per_tuple -= index_qual_cost.per_tuple;
408 run_cost += cpu_per_tuple * tuples_fetched;
410 path->path.startup_cost = startup_cost;
411 path->path.total_cost = startup_cost + run_cost;
415 * index_pages_fetched
416 * Estimate the number of pages actually fetched after accounting for
419 * We use an approximation proposed by Mackert and Lohman, "Index Scans
420 * Using a Finite LRU Buffer: A Validated I/O Model", ACM Transactions
421 * on Database Systems, Vol. 14, No. 3, September 1989, Pages 401-424.
422 * The Mackert and Lohman approximation is that the number of pages
425 * min(2TNs/(2T+Ns), T) when T <= b
426 * 2TNs/(2T+Ns) when T > b and Ns <= 2Tb/(2T-b)
427 * b + (Ns - 2Tb/(2T-b))*(T-b)/T when T > b and Ns > 2Tb/(2T-b)
429 * T = # pages in table
430 * N = # tuples in table
431 * s = selectivity = fraction of table to be scanned
432 * b = # buffer pages available (we include kernel space here)
434 * We assume that effective_cache_size is the total number of buffer pages
435 * available for the whole query, and pro-rate that space across all the
436 * tables in the query and the index currently under consideration. (This
437 * ignores space needed for other indexes used by the query, but since we
438 * don't know which indexes will get used, we can't estimate that very well;
439 * and in any case counting all the tables may well be an overestimate, since
440 * depending on the join plan not all the tables may be scanned concurrently.)
442 * The product Ns is the number of tuples fetched; we pass in that
443 * product rather than calculating it here. "pages" is the number of pages
444 * in the object under consideration (either an index or a table).
445 * "index_pages" is the amount to add to the total table space, which was
446 * computed for us by query_planner.
448 * Caller is expected to have ensured that tuples_fetched is greater than zero
449 * and rounded to integer (see clamp_row_est). The result will likewise be
450 * greater than zero and integral.
453 index_pages_fetched(double tuples_fetched, BlockNumber pages,
454 double index_pages, PlannerInfo *root)
456 double pages_fetched;
461 /* T is # pages in table, but don't allow it to be zero */
462 T = (pages > 1) ? (double) pages : 1.0;
464 /* Compute number of pages assumed to be competing for cache space */
465 total_pages = root->total_table_pages + index_pages;
466 total_pages = Max(total_pages, 1.0);
467 Assert(T <= total_pages);
469 /* b is pro-rated share of effective_cache_size */
470 b = (double) effective_cache_size *T / total_pages;
472 /* force it positive and integral */
478 /* This part is the Mackert and Lohman formula */
482 (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
483 if (pages_fetched >= T)
486 pages_fetched = ceil(pages_fetched);
492 lim = (2.0 * T * b) / (2.0 * T - b);
493 if (tuples_fetched <= lim)
496 (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
501 b + (tuples_fetched - lim) * (T - b) / T;
503 pages_fetched = ceil(pages_fetched);
505 return pages_fetched;
509 * get_indexpath_pages
510 * Determine the total size of the indexes used in a bitmap index path.
512 * Note: if the same index is used more than once in a bitmap tree, we will
513 * count it multiple times, which perhaps is the wrong thing ... but it's
514 * not completely clear, and detecting duplicates is difficult, so ignore it
518 get_indexpath_pages(Path *bitmapqual)
523 if (IsA(bitmapqual, BitmapAndPath))
525 BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
527 foreach(l, apath->bitmapquals)
529 result += get_indexpath_pages((Path *) lfirst(l));
532 else if (IsA(bitmapqual, BitmapOrPath))
534 BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
536 foreach(l, opath->bitmapquals)
538 result += get_indexpath_pages((Path *) lfirst(l));
541 else if (IsA(bitmapqual, IndexPath))
543 IndexPath *ipath = (IndexPath *) bitmapqual;
545 result = (double) ipath->indexinfo->pages;
548 elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
554 * cost_bitmap_heap_scan
555 * Determines and returns the cost of scanning a relation using a bitmap
556 * index-then-heap plan.
558 * 'baserel' is the relation to be scanned
559 * 'bitmapqual' is a tree of IndexPaths, BitmapAndPaths, and BitmapOrPaths
560 * 'outer_rel' is the outer relation when we are considering using the bitmap
561 * scan as the inside of a nestloop join (hence, some of the indexQuals
562 * are join clauses, and we should expect repeated scans of the table);
563 * NULL for a plain bitmap scan
565 * Note: if this is a join inner path, the component IndexPaths in bitmapqual
566 * should have been costed accordingly.
569 cost_bitmap_heap_scan(Path *path, PlannerInfo *root, RelOptInfo *baserel,
570 Path *bitmapqual, RelOptInfo *outer_rel)
572 Cost startup_cost = 0;
575 Selectivity indexSelectivity;
578 double tuples_fetched;
579 double pages_fetched;
580 double spc_seq_page_cost,
581 spc_random_page_cost;
584 /* Should only be applied to base relations */
585 Assert(IsA(baserel, RelOptInfo));
586 Assert(baserel->relid > 0);
587 Assert(baserel->rtekind == RTE_RELATION);
589 if (!enable_bitmapscan)
590 startup_cost += disable_cost;
593 * Fetch total cost of obtaining the bitmap, as well as its total
596 cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
598 startup_cost += indexTotalCost;
600 /* Fetch estimated page costs for tablespace containing table. */
601 get_tablespace_page_costs(baserel->reltablespace,
602 &spc_random_page_cost,
606 * Estimate number of main-table pages fetched.
608 tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
610 T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
612 if (outer_rel != NULL && outer_rel->rows > 1)
615 * For repeated bitmap scans, scale up the number of tuples fetched in
616 * the Mackert and Lohman formula by the number of scans, so that we
617 * estimate the number of pages fetched by all the scans. Then
618 * pro-rate for one scan.
620 double num_scans = outer_rel->rows;
622 pages_fetched = index_pages_fetched(tuples_fetched * num_scans,
624 get_indexpath_pages(bitmapqual),
626 pages_fetched /= num_scans;
631 * For a single scan, the number of heap pages that need to be fetched
632 * is the same as the Mackert and Lohman formula for the case T <= b
633 * (ie, no re-reads needed).
635 pages_fetched = (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
637 if (pages_fetched >= T)
640 pages_fetched = ceil(pages_fetched);
643 * For small numbers of pages we should charge spc_random_page_cost
644 * apiece, while if nearly all the table's pages are being read, it's more
645 * appropriate to charge spc_seq_page_cost apiece. The effect is
646 * nonlinear, too. For lack of a better idea, interpolate like this to
647 * determine the cost per page.
649 if (pages_fetched >= 2.0)
650 cost_per_page = spc_random_page_cost -
651 (spc_random_page_cost - spc_seq_page_cost)
652 * sqrt(pages_fetched / T);
654 cost_per_page = spc_random_page_cost;
656 run_cost += pages_fetched * cost_per_page;
659 * Estimate CPU costs per tuple.
661 * Often the indexquals don't need to be rechecked at each tuple ... but
662 * not always, especially not if there are enough tuples involved that the
663 * bitmaps become lossy. For the moment, just assume they will be
666 startup_cost += baserel->baserestrictcost.startup;
667 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
669 run_cost += cpu_per_tuple * tuples_fetched;
671 path->startup_cost = startup_cost;
672 path->total_cost = startup_cost + run_cost;
676 * cost_bitmap_tree_node
677 * Extract cost and selectivity from a bitmap tree node (index/and/or)
680 cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
682 if (IsA(path, IndexPath))
684 *cost = ((IndexPath *) path)->indextotalcost;
685 *selec = ((IndexPath *) path)->indexselectivity;
688 * Charge a small amount per retrieved tuple to reflect the costs of
689 * manipulating the bitmap. This is mostly to make sure that a bitmap
690 * scan doesn't look to be the same cost as an indexscan to retrieve a
693 *cost += 0.1 * cpu_operator_cost * ((IndexPath *) path)->rows;
695 else if (IsA(path, BitmapAndPath))
697 *cost = path->total_cost;
698 *selec = ((BitmapAndPath *) path)->bitmapselectivity;
700 else if (IsA(path, BitmapOrPath))
702 *cost = path->total_cost;
703 *selec = ((BitmapOrPath *) path)->bitmapselectivity;
707 elog(ERROR, "unrecognized node type: %d", nodeTag(path));
708 *cost = *selec = 0; /* keep compiler quiet */
713 * cost_bitmap_and_node
714 * Estimate the cost of a BitmapAnd node
716 * Note that this considers only the costs of index scanning and bitmap
717 * creation, not the eventual heap access. In that sense the object isn't
718 * truly a Path, but it has enough path-like properties (costs in particular)
719 * to warrant treating it as one.
722 cost_bitmap_and_node(BitmapAndPath *path, PlannerInfo *root)
729 * We estimate AND selectivity on the assumption that the inputs are
730 * independent. This is probably often wrong, but we don't have the info
733 * The runtime cost of the BitmapAnd itself is estimated at 100x
734 * cpu_operator_cost for each tbm_intersect needed. Probably too small,
735 * definitely too simplistic?
739 foreach(l, path->bitmapquals)
741 Path *subpath = (Path *) lfirst(l);
743 Selectivity subselec;
745 cost_bitmap_tree_node(subpath, &subCost, &subselec);
749 totalCost += subCost;
750 if (l != list_head(path->bitmapquals))
751 totalCost += 100.0 * cpu_operator_cost;
753 path->bitmapselectivity = selec;
754 path->path.startup_cost = totalCost;
755 path->path.total_cost = totalCost;
759 * cost_bitmap_or_node
760 * Estimate the cost of a BitmapOr node
762 * See comments for cost_bitmap_and_node.
765 cost_bitmap_or_node(BitmapOrPath *path, PlannerInfo *root)
772 * We estimate OR selectivity on the assumption that the inputs are
773 * non-overlapping, since that's often the case in "x IN (list)" type
774 * situations. Of course, we clamp to 1.0 at the end.
776 * The runtime cost of the BitmapOr itself is estimated at 100x
777 * cpu_operator_cost for each tbm_union needed. Probably too small,
778 * definitely too simplistic? We are aware that the tbm_unions are
779 * optimized out when the inputs are BitmapIndexScans.
783 foreach(l, path->bitmapquals)
785 Path *subpath = (Path *) lfirst(l);
787 Selectivity subselec;
789 cost_bitmap_tree_node(subpath, &subCost, &subselec);
793 totalCost += subCost;
794 if (l != list_head(path->bitmapquals) &&
795 !IsA(subpath, IndexPath))
796 totalCost += 100.0 * cpu_operator_cost;
798 path->bitmapselectivity = Min(selec, 1.0);
799 path->path.startup_cost = totalCost;
800 path->path.total_cost = totalCost;
805 * Determines and returns the cost of scanning a relation using TIDs.
808 cost_tidscan(Path *path, PlannerInfo *root,
809 RelOptInfo *baserel, List *tidquals)
811 Cost startup_cost = 0;
813 bool isCurrentOf = false;
815 QualCost tid_qual_cost;
818 double spc_random_page_cost;
820 /* Should only be applied to base relations */
821 Assert(baserel->relid > 0);
822 Assert(baserel->rtekind == RTE_RELATION);
824 /* Count how many tuples we expect to retrieve */
828 if (IsA(lfirst(l), ScalarArrayOpExpr))
830 /* Each element of the array yields 1 tuple */
831 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) lfirst(l);
832 Node *arraynode = (Node *) lsecond(saop->args);
834 ntuples += estimate_array_length(arraynode);
836 else if (IsA(lfirst(l), CurrentOfExpr))
838 /* CURRENT OF yields 1 tuple */
844 /* It's just CTID = something, count 1 tuple */
850 * We must force TID scan for WHERE CURRENT OF, because only nodeTidscan.c
851 * understands how to do it correctly. Therefore, honor enable_tidscan
852 * only when CURRENT OF isn't present. Also note that cost_qual_eval
853 * counts a CurrentOfExpr as having startup cost disable_cost, which we
854 * subtract off here; that's to prevent other plan types such as seqscan
859 Assert(baserel->baserestrictcost.startup >= disable_cost);
860 startup_cost -= disable_cost;
862 else if (!enable_tidscan)
863 startup_cost += disable_cost;
866 * The TID qual expressions will be computed once, any other baserestrict
867 * quals once per retrived tuple.
869 cost_qual_eval(&tid_qual_cost, tidquals, root);
871 /* fetch estimated page cost for tablespace containing table */
872 get_tablespace_page_costs(baserel->reltablespace,
873 &spc_random_page_cost,
876 /* disk costs --- assume each tuple on a different page */
877 run_cost += spc_random_page_cost * ntuples;
880 startup_cost += baserel->baserestrictcost.startup +
881 tid_qual_cost.per_tuple;
882 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple -
883 tid_qual_cost.per_tuple;
884 run_cost += cpu_per_tuple * ntuples;
886 path->startup_cost = startup_cost;
887 path->total_cost = startup_cost + run_cost;
892 * Determines and returns the cost of scanning a subquery RTE.
895 cost_subqueryscan(Path *path, RelOptInfo *baserel)
901 /* Should only be applied to base relations that are subqueries */
902 Assert(baserel->relid > 0);
903 Assert(baserel->rtekind == RTE_SUBQUERY);
906 * Cost of path is cost of evaluating the subplan, plus cost of evaluating
907 * any restriction clauses that will be attached to the SubqueryScan node,
908 * plus cpu_tuple_cost to account for selection and projection overhead.
910 path->startup_cost = baserel->subplan->startup_cost;
911 path->total_cost = baserel->subplan->total_cost;
913 startup_cost = baserel->baserestrictcost.startup;
914 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
915 run_cost = cpu_per_tuple * baserel->tuples;
917 path->startup_cost += startup_cost;
918 path->total_cost += startup_cost + run_cost;
923 * Determines and returns the cost of scanning a function RTE.
926 cost_functionscan(Path *path, PlannerInfo *root, RelOptInfo *baserel)
928 Cost startup_cost = 0;
934 /* Should only be applied to base relations that are functions */
935 Assert(baserel->relid > 0);
936 rte = planner_rt_fetch(baserel->relid, root);
937 Assert(rte->rtekind == RTE_FUNCTION);
940 * Estimate costs of executing the function expression.
942 * Currently, nodeFunctionscan.c always executes the function to
943 * completion before returning any rows, and caches the results in a
944 * tuplestore. So the function eval cost is all startup cost, and per-row
947 * XXX in principle we ought to charge tuplestore spill costs if the
948 * number of rows is large. However, given how phony our rowcount
949 * estimates for functions tend to be, there's not a lot of point in that
950 * refinement right now.
952 cost_qual_eval_node(&exprcost, rte->funcexpr, root);
954 startup_cost += exprcost.startup + exprcost.per_tuple;
956 /* Add scanning CPU costs */
957 startup_cost += baserel->baserestrictcost.startup;
958 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
959 run_cost += cpu_per_tuple * baserel->tuples;
961 path->startup_cost = startup_cost;
962 path->total_cost = startup_cost + run_cost;
967 * Determines and returns the cost of scanning a VALUES RTE.
970 cost_valuesscan(Path *path, PlannerInfo *root, RelOptInfo *baserel)
972 Cost startup_cost = 0;
976 /* Should only be applied to base relations that are values lists */
977 Assert(baserel->relid > 0);
978 Assert(baserel->rtekind == RTE_VALUES);
981 * For now, estimate list evaluation cost at one operator eval per list
982 * (probably pretty bogus, but is it worth being smarter?)
984 cpu_per_tuple = cpu_operator_cost;
986 /* Add scanning CPU costs */
987 startup_cost += baserel->baserestrictcost.startup;
988 cpu_per_tuple += cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
989 run_cost += cpu_per_tuple * baserel->tuples;
991 path->startup_cost = startup_cost;
992 path->total_cost = startup_cost + run_cost;
997 * Determines and returns the cost of scanning a CTE RTE.
999 * Note: this is used for both self-reference and regular CTEs; the
1000 * possible cost differences are below the threshold of what we could
1001 * estimate accurately anyway. Note that the costs of evaluating the
1002 * referenced CTE query are added into the final plan as initplan costs,
1003 * and should NOT be counted here.
1006 cost_ctescan(Path *path, PlannerInfo *root, RelOptInfo *baserel)
1008 Cost startup_cost = 0;
1012 /* Should only be applied to base relations that are CTEs */
1013 Assert(baserel->relid > 0);
1014 Assert(baserel->rtekind == RTE_CTE);
1016 /* Charge one CPU tuple cost per row for tuplestore manipulation */
1017 cpu_per_tuple = cpu_tuple_cost;
1019 /* Add scanning CPU costs */
1020 startup_cost += baserel->baserestrictcost.startup;
1021 cpu_per_tuple += cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
1022 run_cost += cpu_per_tuple * baserel->tuples;
1024 path->startup_cost = startup_cost;
1025 path->total_cost = startup_cost + run_cost;
1029 * cost_recursive_union
1030 * Determines and returns the cost of performing a recursive union,
1031 * and also the estimated output size.
1033 * We are given Plans for the nonrecursive and recursive terms.
1035 * Note that the arguments and output are Plans, not Paths as in most of
1036 * the rest of this module. That's because we don't bother setting up a
1037 * Path representation for recursive union --- we have only one way to do it.
1040 cost_recursive_union(Plan *runion, Plan *nrterm, Plan *rterm)
1046 /* We probably have decent estimates for the non-recursive term */
1047 startup_cost = nrterm->startup_cost;
1048 total_cost = nrterm->total_cost;
1049 total_rows = nrterm->plan_rows;
1052 * We arbitrarily assume that about 10 recursive iterations will be
1053 * needed, and that we've managed to get a good fix on the cost and output
1054 * size of each one of them. These are mighty shaky assumptions but it's
1055 * hard to see how to do better.
1057 total_cost += 10 * rterm->total_cost;
1058 total_rows += 10 * rterm->plan_rows;
1061 * Also charge cpu_tuple_cost per row to account for the costs of
1062 * manipulating the tuplestores. (We don't worry about possible
1063 * spill-to-disk costs.)
1065 total_cost += cpu_tuple_cost * total_rows;
1067 runion->startup_cost = startup_cost;
1068 runion->total_cost = total_cost;
1069 runion->plan_rows = total_rows;
1070 runion->plan_width = Max(nrterm->plan_width, rterm->plan_width);
1075 * Determines and returns the cost of sorting a relation, including
1076 * the cost of reading the input data.
1078 * If the total volume of data to sort is less than sort_mem, we will do
1079 * an in-memory sort, which requires no I/O and about t*log2(t) tuple
1080 * comparisons for t tuples.
1082 * If the total volume exceeds sort_mem, we switch to a tape-style merge
1083 * algorithm. There will still be about t*log2(t) tuple comparisons in
1084 * total, but we will also need to write and read each tuple once per
1085 * merge pass. We expect about ceil(logM(r)) merge passes where r is the
1086 * number of initial runs formed and M is the merge order used by tuplesort.c.
1087 * Since the average initial run should be about twice sort_mem, we have
1088 * disk traffic = 2 * relsize * ceil(logM(p / (2*sort_mem)))
1089 * cpu = comparison_cost * t * log2(t)
1091 * If the sort is bounded (i.e., only the first k result tuples are needed)
1092 * and k tuples can fit into sort_mem, we use a heap method that keeps only
1093 * k tuples in the heap; this will require about t*log2(k) tuple comparisons.
1095 * The disk traffic is assumed to be 3/4ths sequential and 1/4th random
1096 * accesses (XXX can't we refine that guess?)
1098 * By default, we charge two operator evals per tuple comparison, which should
1099 * be in the right ballpark in most cases. The caller can tweak this by
1100 * specifying nonzero comparison_cost; typically that's used for any extra
1101 * work that has to be done to prepare the inputs to the comparison operators.
1103 * 'pathkeys' is a list of sort keys
1104 * 'input_cost' is the total cost for reading the input data
1105 * 'tuples' is the number of tuples in the relation
1106 * 'width' is the average tuple width in bytes
1107 * 'comparison_cost' is the extra cost per comparison, if any
1108 * 'sort_mem' is the number of kilobytes of work memory allowed for the sort
1109 * 'limit_tuples' is the bound on the number of output tuples; -1 if no bound
1111 * NOTE: some callers currently pass NIL for pathkeys because they
1112 * can't conveniently supply the sort keys. Since this routine doesn't
1113 * currently do anything with pathkeys anyway, that doesn't matter...
1114 * but if it ever does, it should react gracefully to lack of key data.
1115 * (Actually, the thing we'd most likely be interested in is just the number
1116 * of sort keys, which all callers *could* supply.)
1119 cost_sort(Path *path, PlannerInfo *root,
1120 List *pathkeys, Cost input_cost, double tuples, int width,
1121 Cost comparison_cost, int sort_mem,
1122 double limit_tuples)
1124 Cost startup_cost = input_cost;
1126 double input_bytes = relation_byte_size(tuples, width);
1127 double output_bytes;
1128 double output_tuples;
1129 long sort_mem_bytes = sort_mem * 1024L;
1132 startup_cost += disable_cost;
1135 * We want to be sure the cost of a sort is never estimated as zero, even
1136 * if passed-in tuple count is zero. Besides, mustn't do log(0)...
1141 /* Include the default cost-per-comparison */
1142 comparison_cost += 2.0 * cpu_operator_cost;
1144 /* Do we have a useful LIMIT? */
1145 if (limit_tuples > 0 && limit_tuples < tuples)
1147 output_tuples = limit_tuples;
1148 output_bytes = relation_byte_size(output_tuples, width);
1152 output_tuples = tuples;
1153 output_bytes = input_bytes;
1156 if (output_bytes > sort_mem_bytes)
1159 * We'll have to use a disk-based sort of all the tuples
1161 double npages = ceil(input_bytes / BLCKSZ);
1162 double nruns = (input_bytes / sort_mem_bytes) * 0.5;
1163 double mergeorder = tuplesort_merge_order(sort_mem_bytes);
1165 double npageaccesses;
1170 * Assume about N log2 N comparisons
1172 startup_cost += comparison_cost * tuples * LOG2(tuples);
1176 /* Compute logM(r) as log(r) / log(M) */
1177 if (nruns > mergeorder)
1178 log_runs = ceil(log(nruns) / log(mergeorder));
1181 npageaccesses = 2.0 * npages * log_runs;
1182 /* Assume 3/4ths of accesses are sequential, 1/4th are not */
1183 startup_cost += npageaccesses *
1184 (seq_page_cost * 0.75 + random_page_cost * 0.25);
1186 else if (tuples > 2 * output_tuples || input_bytes > sort_mem_bytes)
1189 * We'll use a bounded heap-sort keeping just K tuples in memory, for
1190 * a total number of tuple comparisons of N log2 K; but the constant
1191 * factor is a bit higher than for quicksort. Tweak it so that the
1192 * cost curve is continuous at the crossover point.
1194 startup_cost += comparison_cost * tuples * LOG2(2.0 * output_tuples);
1198 /* We'll use plain quicksort on all the input tuples */
1199 startup_cost += comparison_cost * tuples * LOG2(tuples);
1203 * Also charge a small amount (arbitrarily set equal to operator cost) per
1204 * extracted tuple. We don't charge cpu_tuple_cost because a Sort node
1205 * doesn't do qual-checking or projection, so it has less overhead than
1206 * most plan nodes. Note it's correct to use tuples not output_tuples
1207 * here --- the upper LIMIT will pro-rate the run cost so we'd be double
1208 * counting the LIMIT otherwise.
1210 run_cost += cpu_operator_cost * tuples;
1212 path->startup_cost = startup_cost;
1213 path->total_cost = startup_cost + run_cost;
1218 * Determines and returns the cost of a MergeAppend node.
1220 * MergeAppend merges several pre-sorted input streams, using a heap that
1221 * at any given instant holds the next tuple from each stream. If there
1222 * are N streams, we need about N*log2(N) tuple comparisons to construct
1223 * the heap at startup, and then for each output tuple, about log2(N)
1224 * comparisons to delete the top heap entry and another log2(N) comparisons
1225 * to insert its successor from the same stream.
1227 * (The effective value of N will drop once some of the input streams are
1228 * exhausted, but it seems unlikely to be worth trying to account for that.)
1230 * The heap is never spilled to disk, since we assume N is not very large.
1231 * So this is much simpler than cost_sort.
1233 * As in cost_sort, we charge two operator evals per tuple comparison.
1235 * 'pathkeys' is a list of sort keys
1236 * 'n_streams' is the number of input streams
1237 * 'input_startup_cost' is the sum of the input streams' startup costs
1238 * 'input_total_cost' is the sum of the input streams' total costs
1239 * 'tuples' is the number of tuples in all the streams
1242 cost_merge_append(Path *path, PlannerInfo *root,
1243 List *pathkeys, int n_streams,
1244 Cost input_startup_cost, Cost input_total_cost,
1247 Cost startup_cost = 0;
1249 Cost comparison_cost;
1256 N = (n_streams < 2) ? 2.0 : (double) n_streams;
1259 /* Assumed cost per tuple comparison */
1260 comparison_cost = 2.0 * cpu_operator_cost;
1262 /* Heap creation cost */
1263 startup_cost += comparison_cost * N * logN;
1265 /* Per-tuple heap maintenance cost */
1266 run_cost += tuples * comparison_cost * 2.0 * logN;
1269 * Also charge a small amount (arbitrarily set equal to operator cost) per
1270 * extracted tuple. We don't charge cpu_tuple_cost because a MergeAppend
1271 * node doesn't do qual-checking or projection, so it has less overhead
1272 * than most plan nodes.
1274 run_cost += cpu_operator_cost * tuples;
1276 path->startup_cost = startup_cost + input_startup_cost;
1277 path->total_cost = startup_cost + run_cost + input_total_cost;
1282 * Determines and returns the cost of materializing a relation, including
1283 * the cost of reading the input data.
1285 * If the total volume of data to materialize exceeds work_mem, we will need
1286 * to write it to disk, so the cost is much higher in that case.
1288 * Note that here we are estimating the costs for the first scan of the
1289 * relation, so the materialization is all overhead --- any savings will
1290 * occur only on rescan, which is estimated in cost_rescan.
1293 cost_material(Path *path,
1294 Cost input_startup_cost, Cost input_total_cost,
1295 double tuples, int width)
1297 Cost startup_cost = input_startup_cost;
1298 Cost run_cost = input_total_cost - input_startup_cost;
1299 double nbytes = relation_byte_size(tuples, width);
1300 long work_mem_bytes = work_mem * 1024L;
1303 * Whether spilling or not, charge 2x cpu_operator_cost per tuple to
1304 * reflect bookkeeping overhead. (This rate must be more than what
1305 * cost_rescan charges for materialize, ie, cpu_operator_cost per tuple;
1306 * if it is exactly the same then there will be a cost tie between
1307 * nestloop with A outer, materialized B inner and nestloop with B outer,
1308 * materialized A inner. The extra cost ensures we'll prefer
1309 * materializing the smaller rel.) Note that this is normally a good deal
1310 * less than cpu_tuple_cost; which is OK because a Material plan node
1311 * doesn't do qual-checking or projection, so it's got less overhead than
1314 run_cost += 2 * cpu_operator_cost * tuples;
1317 * If we will spill to disk, charge at the rate of seq_page_cost per page.
1318 * This cost is assumed to be evenly spread through the plan run phase,
1319 * which isn't exactly accurate but our cost model doesn't allow for
1320 * nonuniform costs within the run phase.
1322 if (nbytes > work_mem_bytes)
1324 double npages = ceil(nbytes / BLCKSZ);
1326 run_cost += seq_page_cost * npages;
1329 path->startup_cost = startup_cost;
1330 path->total_cost = startup_cost + run_cost;
1335 * Determines and returns the cost of performing an Agg plan node,
1336 * including the cost of its input.
1338 * Note: when aggstrategy == AGG_SORTED, caller must ensure that input costs
1339 * are for appropriately-sorted input.
1342 cost_agg(Path *path, PlannerInfo *root,
1343 AggStrategy aggstrategy, int numAggs,
1344 int numGroupCols, double numGroups,
1345 Cost input_startup_cost, Cost input_total_cost,
1346 double input_tuples)
1352 * We charge one cpu_operator_cost per aggregate function per input tuple,
1353 * and another one per output tuple (corresponding to transfn and finalfn
1354 * calls respectively). If we are grouping, we charge an additional
1355 * cpu_operator_cost per grouping column per input tuple for grouping
1358 * We will produce a single output tuple if not grouping, and a tuple per
1359 * group otherwise. We charge cpu_tuple_cost for each output tuple.
1361 * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the
1362 * same total CPU cost, but AGG_SORTED has lower startup cost. If the
1363 * input path is already sorted appropriately, AGG_SORTED should be
1364 * preferred (since it has no risk of memory overflow). This will happen
1365 * as long as the computed total costs are indeed exactly equal --- but if
1366 * there's roundoff error we might do the wrong thing. So be sure that
1367 * the computations below form the same intermediate values in the same
1370 * Note: ideally we should use the pg_proc.procost costs of each
1371 * aggregate's component functions, but for now that seems like an
1372 * excessive amount of work.
1374 if (aggstrategy == AGG_PLAIN)
1376 startup_cost = input_total_cost;
1377 startup_cost += cpu_operator_cost * (input_tuples + 1) * numAggs;
1378 /* we aren't grouping */
1379 total_cost = startup_cost + cpu_tuple_cost;
1381 else if (aggstrategy == AGG_SORTED)
1383 /* Here we are able to deliver output on-the-fly */
1384 startup_cost = input_startup_cost;
1385 total_cost = input_total_cost;
1386 /* calcs phrased this way to match HASHED case, see note above */
1387 total_cost += cpu_operator_cost * input_tuples * numGroupCols;
1388 total_cost += cpu_operator_cost * input_tuples * numAggs;
1389 total_cost += cpu_operator_cost * numGroups * numAggs;
1390 total_cost += cpu_tuple_cost * numGroups;
1394 /* must be AGG_HASHED */
1395 startup_cost = input_total_cost;
1396 startup_cost += cpu_operator_cost * input_tuples * numGroupCols;
1397 startup_cost += cpu_operator_cost * input_tuples * numAggs;
1398 total_cost = startup_cost;
1399 total_cost += cpu_operator_cost * numGroups * numAggs;
1400 total_cost += cpu_tuple_cost * numGroups;
1403 path->startup_cost = startup_cost;
1404 path->total_cost = total_cost;
1409 * Determines and returns the cost of performing a WindowAgg plan node,
1410 * including the cost of its input.
1412 * Input is assumed already properly sorted.
1415 cost_windowagg(Path *path, PlannerInfo *root,
1416 int numWindowFuncs, int numPartCols, int numOrderCols,
1417 Cost input_startup_cost, Cost input_total_cost,
1418 double input_tuples)
1423 startup_cost = input_startup_cost;
1424 total_cost = input_total_cost;
1427 * We charge one cpu_operator_cost per window function per tuple (often a
1428 * drastic underestimate, but without a way to gauge how many tuples the
1429 * window function will fetch, it's hard to do better). We also charge
1430 * cpu_operator_cost per grouping column per tuple for grouping
1431 * comparisons, plus cpu_tuple_cost per tuple for general overhead.
1433 total_cost += cpu_operator_cost * input_tuples * numWindowFuncs;
1434 total_cost += cpu_operator_cost * input_tuples * (numPartCols + numOrderCols);
1435 total_cost += cpu_tuple_cost * input_tuples;
1437 path->startup_cost = startup_cost;
1438 path->total_cost = total_cost;
1443 * Determines and returns the cost of performing a Group plan node,
1444 * including the cost of its input.
1446 * Note: caller must ensure that input costs are for appropriately-sorted
1450 cost_group(Path *path, PlannerInfo *root,
1451 int numGroupCols, double numGroups,
1452 Cost input_startup_cost, Cost input_total_cost,
1453 double input_tuples)
1458 startup_cost = input_startup_cost;
1459 total_cost = input_total_cost;
1462 * Charge one cpu_operator_cost per comparison per input tuple. We assume
1463 * all columns get compared at most of the tuples.
1465 total_cost += cpu_operator_cost * input_tuples * numGroupCols;
1467 path->startup_cost = startup_cost;
1468 path->total_cost = total_cost;
1472 * If a nestloop's inner path is an indexscan, be sure to use its estimated
1473 * output row count, which may be lower than the restriction-clause-only row
1474 * count of its parent. (We don't include this case in the PATH_ROWS macro
1475 * because it applies *only* to a nestloop's inner relation.) We have to
1476 * be prepared to recurse through Append or MergeAppend nodes in case of an
1477 * appendrel. (It's not clear MergeAppend can be seen here, but we may as
1478 * well handle it if so.)
1481 nestloop_inner_path_rows(Path *path)
1485 if (IsA(path, IndexPath))
1486 result = ((IndexPath *) path)->rows;
1487 else if (IsA(path, BitmapHeapPath))
1488 result = ((BitmapHeapPath *) path)->rows;
1489 else if (IsA(path, AppendPath))
1494 foreach(l, ((AppendPath *) path)->subpaths)
1496 result += nestloop_inner_path_rows((Path *) lfirst(l));
1499 else if (IsA(path, MergeAppendPath))
1504 foreach(l, ((MergeAppendPath *) path)->subpaths)
1506 result += nestloop_inner_path_rows((Path *) lfirst(l));
1510 result = PATH_ROWS(path);
1517 * Determines and returns the cost of joining two relations using the
1518 * nested loop algorithm.
1520 * 'path' is already filled in except for the cost fields
1521 * 'sjinfo' is extra info about the join for selectivity estimation
1524 cost_nestloop(NestPath *path, PlannerInfo *root, SpecialJoinInfo *sjinfo)
1526 Path *outer_path = path->outerjoinpath;
1527 Path *inner_path = path->innerjoinpath;
1528 Cost startup_cost = 0;
1530 Cost inner_rescan_start_cost;
1531 Cost inner_rescan_total_cost;
1532 Cost inner_run_cost;
1533 Cost inner_rescan_run_cost;
1535 QualCost restrict_qual_cost;
1536 double outer_path_rows = PATH_ROWS(outer_path);
1537 double inner_path_rows = nestloop_inner_path_rows(inner_path);
1539 Selectivity outer_match_frac;
1540 Selectivity match_count;
1541 bool indexed_join_quals;
1543 if (!enable_nestloop)
1544 startup_cost += disable_cost;
1546 /* estimate costs to rescan the inner relation */
1547 cost_rescan(root, inner_path,
1548 &inner_rescan_start_cost,
1549 &inner_rescan_total_cost);
1551 /* cost of source data */
1554 * NOTE: clearly, we must pay both outer and inner paths' startup_cost
1555 * before we can start returning tuples, so the join's startup cost is
1556 * their sum. We'll also pay the inner path's rescan startup cost
1559 startup_cost += outer_path->startup_cost + inner_path->startup_cost;
1560 run_cost += outer_path->total_cost - outer_path->startup_cost;
1561 if (outer_path_rows > 1)
1562 run_cost += (outer_path_rows - 1) * inner_rescan_start_cost;
1564 inner_run_cost = inner_path->total_cost - inner_path->startup_cost;
1565 inner_rescan_run_cost = inner_rescan_total_cost - inner_rescan_start_cost;
1567 if (adjust_semi_join(root, path, sjinfo,
1570 &indexed_join_quals))
1572 double outer_matched_rows;
1573 Selectivity inner_scan_frac;
1576 * SEMI or ANTI join: executor will stop after first match.
1578 * For an outer-rel row that has at least one match, we can expect the
1579 * inner scan to stop after a fraction 1/(match_count+1) of the inner
1580 * rows, if the matches are evenly distributed. Since they probably
1581 * aren't quite evenly distributed, we apply a fuzz factor of 2.0 to
1582 * that fraction. (If we used a larger fuzz factor, we'd have to
1583 * clamp inner_scan_frac to at most 1.0; but since match_count is at
1584 * least 1, no such clamp is needed now.)
1586 * A complicating factor is that rescans may be cheaper than first
1587 * scans. If we never scan all the way to the end of the inner rel,
1588 * it might be (depending on the plan type) that we'd never pay the
1589 * whole inner first-scan run cost. However it is difficult to
1590 * estimate whether that will happen, so be conservative and always
1591 * charge the whole first-scan cost once.
1593 run_cost += inner_run_cost;
1595 outer_matched_rows = rint(outer_path_rows * outer_match_frac);
1596 inner_scan_frac = 2.0 / (match_count + 1.0);
1598 /* Add inner run cost for additional outer tuples having matches */
1599 if (outer_matched_rows > 1)
1600 run_cost += (outer_matched_rows - 1) * inner_rescan_run_cost * inner_scan_frac;
1602 /* Compute number of tuples processed (not number emitted!) */
1603 ntuples = outer_matched_rows * inner_path_rows * inner_scan_frac;
1606 * For unmatched outer-rel rows, there are two cases. If the inner
1607 * path is an indexscan using all the joinquals as indexquals, then an
1608 * unmatched row results in an indexscan returning no rows, which is
1609 * probably quite cheap. We estimate this case as the same cost to
1610 * return the first tuple of a nonempty scan. Otherwise, the executor
1611 * will have to scan the whole inner rel; not so cheap.
1613 if (indexed_join_quals)
1615 run_cost += (outer_path_rows - outer_matched_rows) *
1616 inner_rescan_run_cost / inner_path_rows;
1619 * We won't be evaluating any quals at all for these rows, so
1620 * don't add them to ntuples.
1625 run_cost += (outer_path_rows - outer_matched_rows) *
1626 inner_rescan_run_cost;
1627 ntuples += (outer_path_rows - outer_matched_rows) *
1633 /* Normal case; we'll scan whole input rel for each outer row */
1634 run_cost += inner_run_cost;
1635 if (outer_path_rows > 1)
1636 run_cost += (outer_path_rows - 1) * inner_rescan_run_cost;
1638 /* Compute number of tuples processed (not number emitted!) */
1639 ntuples = outer_path_rows * inner_path_rows;
1643 cost_qual_eval(&restrict_qual_cost, path->joinrestrictinfo, root);
1644 startup_cost += restrict_qual_cost.startup;
1645 cpu_per_tuple = cpu_tuple_cost + restrict_qual_cost.per_tuple;
1646 run_cost += cpu_per_tuple * ntuples;
1648 path->path.startup_cost = startup_cost;
1649 path->path.total_cost = startup_cost + run_cost;
1654 * Determines and returns the cost of joining two relations using the
1655 * merge join algorithm.
1657 * Unlike other costsize functions, this routine makes one actual decision:
1658 * whether we should materialize the inner path. We do that either because
1659 * the inner path can't support mark/restore, or because it's cheaper to
1660 * use an interposed Material node to handle mark/restore. When the decision
1661 * is cost-based it would be logically cleaner to build and cost two separate
1662 * paths with and without that flag set; but that would require repeating most
1663 * of the calculations here, which are not all that cheap. Since the choice
1664 * will not affect output pathkeys or startup cost, only total cost, there is
1665 * no possibility of wanting to keep both paths. So it seems best to make
1666 * the decision here and record it in the path's materialize_inner field.
1668 * 'path' is already filled in except for the cost fields and materialize_inner
1669 * 'sjinfo' is extra info about the join for selectivity estimation
1671 * Notes: path's mergeclauses should be a subset of the joinrestrictinfo list;
1672 * outersortkeys and innersortkeys are lists of the keys to be used
1673 * to sort the outer and inner relations, or NIL if no explicit
1674 * sort is needed because the source path is already ordered.
1677 cost_mergejoin(MergePath *path, PlannerInfo *root, SpecialJoinInfo *sjinfo)
1679 Path *outer_path = path->jpath.outerjoinpath;
1680 Path *inner_path = path->jpath.innerjoinpath;
1681 List *mergeclauses = path->path_mergeclauses;
1682 List *outersortkeys = path->outersortkeys;
1683 List *innersortkeys = path->innersortkeys;
1684 Cost startup_cost = 0;
1690 QualCost merge_qual_cost;
1691 QualCost qp_qual_cost;
1692 double outer_path_rows = PATH_ROWS(outer_path);
1693 double inner_path_rows = PATH_ROWS(inner_path);
1698 double mergejointuples,
1701 Selectivity outerstartsel,
1705 Path sort_path; /* dummy for result of cost_sort */
1707 /* Protect some assumptions below that rowcounts aren't zero */
1708 if (outer_path_rows <= 0)
1709 outer_path_rows = 1;
1710 if (inner_path_rows <= 0)
1711 inner_path_rows = 1;
1713 if (!enable_mergejoin)
1714 startup_cost += disable_cost;
1717 * Compute cost of the mergequals and qpquals (other restriction clauses)
1720 cost_qual_eval(&merge_qual_cost, mergeclauses, root);
1721 cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
1722 qp_qual_cost.startup -= merge_qual_cost.startup;
1723 qp_qual_cost.per_tuple -= merge_qual_cost.per_tuple;
1726 * Get approx # tuples passing the mergequals. We use approx_tuple_count
1727 * here because we need an estimate done with JOIN_INNER semantics.
1729 mergejointuples = approx_tuple_count(root, &path->jpath, mergeclauses);
1732 * When there are equal merge keys in the outer relation, the mergejoin
1733 * must rescan any matching tuples in the inner relation. This means
1734 * re-fetching inner tuples; we have to estimate how often that happens.
1736 * For regular inner and outer joins, the number of re-fetches can be
1737 * estimated approximately as size of merge join output minus size of
1738 * inner relation. Assume that the distinct key values are 1, 2, ..., and
1739 * denote the number of values of each key in the outer relation as m1,
1740 * m2, ...; in the inner relation, n1, n2, ... Then we have
1742 * size of join = m1 * n1 + m2 * n2 + ...
1744 * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... = m1 *
1745 * n1 + m2 * n2 + ... - (n1 + n2 + ...) = size of join - size of inner
1748 * This equation works correctly for outer tuples having no inner match
1749 * (nk = 0), but not for inner tuples having no outer match (mk = 0); we
1750 * are effectively subtracting those from the number of rescanned tuples,
1751 * when we should not. Can we do better without expensive selectivity
1754 * The whole issue is moot if we are working from a unique-ified outer
1757 if (IsA(outer_path, UniquePath))
1758 rescannedtuples = 0;
1761 rescannedtuples = mergejointuples - inner_path_rows;
1762 /* Must clamp because of possible underestimate */
1763 if (rescannedtuples < 0)
1764 rescannedtuples = 0;
1766 /* We'll inflate various costs this much to account for rescanning */
1767 rescanratio = 1.0 + (rescannedtuples / inner_path_rows);
1770 * A merge join will stop as soon as it exhausts either input stream
1771 * (unless it's an outer join, in which case the outer side has to be
1772 * scanned all the way anyway). Estimate fraction of the left and right
1773 * inputs that will actually need to be scanned. Likewise, we can
1774 * estimate the number of rows that will be skipped before the first join
1775 * pair is found, which should be factored into startup cost. We use only
1776 * the first (most significant) merge clause for this purpose. Since
1777 * mergejoinscansel() is a fairly expensive computation, we cache the
1778 * results in the merge clause RestrictInfo.
1780 if (mergeclauses && path->jpath.jointype != JOIN_FULL)
1782 RestrictInfo *firstclause = (RestrictInfo *) linitial(mergeclauses);
1787 MergeScanSelCache *cache;
1789 /* Get the input pathkeys to determine the sort-order details */
1790 opathkeys = outersortkeys ? outersortkeys : outer_path->pathkeys;
1791 ipathkeys = innersortkeys ? innersortkeys : inner_path->pathkeys;
1794 opathkey = (PathKey *) linitial(opathkeys);
1795 ipathkey = (PathKey *) linitial(ipathkeys);
1796 /* debugging check */
1797 if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
1798 opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation ||
1799 opathkey->pk_strategy != ipathkey->pk_strategy ||
1800 opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
1801 elog(ERROR, "left and right pathkeys do not match in mergejoin");
1803 /* Get the selectivity with caching */
1804 cache = cached_scansel(root, firstclause, opathkey);
1806 if (bms_is_subset(firstclause->left_relids,
1807 outer_path->parent->relids))
1809 /* left side of clause is outer */
1810 outerstartsel = cache->leftstartsel;
1811 outerendsel = cache->leftendsel;
1812 innerstartsel = cache->rightstartsel;
1813 innerendsel = cache->rightendsel;
1817 /* left side of clause is inner */
1818 outerstartsel = cache->rightstartsel;
1819 outerendsel = cache->rightendsel;
1820 innerstartsel = cache->leftstartsel;
1821 innerendsel = cache->leftendsel;
1823 if (path->jpath.jointype == JOIN_LEFT ||
1824 path->jpath.jointype == JOIN_ANTI)
1826 outerstartsel = 0.0;
1829 else if (path->jpath.jointype == JOIN_RIGHT)
1831 innerstartsel = 0.0;
1837 /* cope with clauseless or full mergejoin */
1838 outerstartsel = innerstartsel = 0.0;
1839 outerendsel = innerendsel = 1.0;
1843 * Convert selectivities to row counts. We force outer_rows and
1844 * inner_rows to be at least 1, but the skip_rows estimates can be zero.
1846 outer_skip_rows = rint(outer_path_rows * outerstartsel);
1847 inner_skip_rows = rint(inner_path_rows * innerstartsel);
1848 outer_rows = clamp_row_est(outer_path_rows * outerendsel);
1849 inner_rows = clamp_row_est(inner_path_rows * innerendsel);
1851 Assert(outer_skip_rows <= outer_rows);
1852 Assert(inner_skip_rows <= inner_rows);
1855 * Readjust scan selectivities to account for above rounding. This is
1856 * normally an insignificant effect, but when there are only a few rows in
1857 * the inputs, failing to do this makes for a large percentage error.
1859 outerstartsel = outer_skip_rows / outer_path_rows;
1860 innerstartsel = inner_skip_rows / inner_path_rows;
1861 outerendsel = outer_rows / outer_path_rows;
1862 innerendsel = inner_rows / inner_path_rows;
1864 Assert(outerstartsel <= outerendsel);
1865 Assert(innerstartsel <= innerendsel);
1867 /* cost of source data */
1869 if (outersortkeys) /* do we need to sort outer? */
1871 cost_sort(&sort_path,
1874 outer_path->total_cost,
1876 outer_path->parent->width,
1880 startup_cost += sort_path.startup_cost;
1881 startup_cost += (sort_path.total_cost - sort_path.startup_cost)
1883 run_cost += (sort_path.total_cost - sort_path.startup_cost)
1884 * (outerendsel - outerstartsel);
1888 startup_cost += outer_path->startup_cost;
1889 startup_cost += (outer_path->total_cost - outer_path->startup_cost)
1891 run_cost += (outer_path->total_cost - outer_path->startup_cost)
1892 * (outerendsel - outerstartsel);
1895 if (innersortkeys) /* do we need to sort inner? */
1897 cost_sort(&sort_path,
1900 inner_path->total_cost,
1902 inner_path->parent->width,
1906 startup_cost += sort_path.startup_cost;
1907 startup_cost += (sort_path.total_cost - sort_path.startup_cost)
1909 inner_run_cost = (sort_path.total_cost - sort_path.startup_cost)
1910 * (innerendsel - innerstartsel);
1914 startup_cost += inner_path->startup_cost;
1915 startup_cost += (inner_path->total_cost - inner_path->startup_cost)
1917 inner_run_cost = (inner_path->total_cost - inner_path->startup_cost)
1918 * (innerendsel - innerstartsel);
1922 * Decide whether we want to materialize the inner input to shield it from
1923 * mark/restore and performing re-fetches. Our cost model for regular
1924 * re-fetches is that a re-fetch costs the same as an original fetch,
1925 * which is probably an overestimate; but on the other hand we ignore the
1926 * bookkeeping costs of mark/restore. Not clear if it's worth developing
1927 * a more refined model. So we just need to inflate the inner run cost by
1930 bare_inner_cost = inner_run_cost * rescanratio;
1933 * When we interpose a Material node the re-fetch cost is assumed to be
1934 * just cpu_operator_cost per tuple, independently of the underlying
1935 * plan's cost; and we charge an extra cpu_operator_cost per original
1936 * fetch as well. Note that we're assuming the materialize node will
1937 * never spill to disk, since it only has to remember tuples back to the
1938 * last mark. (If there are a huge number of duplicates, our other cost
1939 * factors will make the path so expensive that it probably won't get
1940 * chosen anyway.) So we don't use cost_rescan here.
1942 * Note: keep this estimate in sync with create_mergejoin_plan's labeling
1943 * of the generated Material node.
1945 mat_inner_cost = inner_run_cost +
1946 cpu_operator_cost * inner_path_rows * rescanratio;
1949 * Prefer materializing if it looks cheaper, unless the user has asked to
1950 * suppress materialization.
1952 if (enable_material && mat_inner_cost < bare_inner_cost)
1953 path->materialize_inner = true;
1956 * Even if materializing doesn't look cheaper, we *must* do it if the
1957 * inner path is to be used directly (without sorting) and it doesn't
1958 * support mark/restore.
1960 * Since the inner side must be ordered, and only Sorts and IndexScans can
1961 * create order to begin with, and they both support mark/restore, you
1962 * might think there's no problem --- but you'd be wrong. Nestloop and
1963 * merge joins can *preserve* the order of their inputs, so they can be
1964 * selected as the input of a mergejoin, and they don't support
1965 * mark/restore at present.
1967 * We don't test the value of enable_material here, because
1968 * materialization is required for correctness in this case, and turning
1969 * it off does not entitle us to deliver an invalid plan.
1971 else if (innersortkeys == NIL &&
1972 !ExecSupportsMarkRestore(inner_path->pathtype))
1973 path->materialize_inner = true;
1976 * Also, force materializing if the inner path is to be sorted and the
1977 * sort is expected to spill to disk. This is because the final merge
1978 * pass can be done on-the-fly if it doesn't have to support mark/restore.
1979 * We don't try to adjust the cost estimates for this consideration,
1982 * Since materialization is a performance optimization in this case,
1983 * rather than necessary for correctness, we skip it if enable_material is
1986 else if (enable_material && innersortkeys != NIL &&
1987 relation_byte_size(inner_path_rows, inner_path->parent->width) >
1989 path->materialize_inner = true;
1991 path->materialize_inner = false;
1993 /* Charge the right incremental cost for the chosen case */
1994 if (path->materialize_inner)
1995 run_cost += mat_inner_cost;
1997 run_cost += bare_inner_cost;
2002 * The number of tuple comparisons needed is approximately number of outer
2003 * rows plus number of inner rows plus number of rescanned tuples (can we
2004 * refine this?). At each one, we need to evaluate the mergejoin quals.
2006 startup_cost += merge_qual_cost.startup;
2007 startup_cost += merge_qual_cost.per_tuple *
2008 (outer_skip_rows + inner_skip_rows * rescanratio);
2009 run_cost += merge_qual_cost.per_tuple *
2010 ((outer_rows - outer_skip_rows) +
2011 (inner_rows - inner_skip_rows) * rescanratio);
2014 * For each tuple that gets through the mergejoin proper, we charge
2015 * cpu_tuple_cost plus the cost of evaluating additional restriction
2016 * clauses that are to be applied at the join. (This is pessimistic since
2017 * not all of the quals may get evaluated at each tuple.)
2019 * Note: we could adjust for SEMI/ANTI joins skipping some qual
2020 * evaluations here, but it's probably not worth the trouble.
2022 startup_cost += qp_qual_cost.startup;
2023 cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
2024 run_cost += cpu_per_tuple * mergejointuples;
2026 path->jpath.path.startup_cost = startup_cost;
2027 path->jpath.path.total_cost = startup_cost + run_cost;
2031 * run mergejoinscansel() with caching
2033 static MergeScanSelCache *
2034 cached_scansel(PlannerInfo *root, RestrictInfo *rinfo, PathKey *pathkey)
2036 MergeScanSelCache *cache;
2038 Selectivity leftstartsel,
2042 MemoryContext oldcontext;
2044 /* Do we have this result already? */
2045 foreach(lc, rinfo->scansel_cache)
2047 cache = (MergeScanSelCache *) lfirst(lc);
2048 if (cache->opfamily == pathkey->pk_opfamily &&
2049 cache->collation == pathkey->pk_eclass->ec_collation &&
2050 cache->strategy == pathkey->pk_strategy &&
2051 cache->nulls_first == pathkey->pk_nulls_first)
2055 /* Nope, do the computation */
2056 mergejoinscansel(root,
2057 (Node *) rinfo->clause,
2058 pathkey->pk_opfamily,
2059 pathkey->pk_strategy,
2060 pathkey->pk_nulls_first,
2066 /* Cache the result in suitably long-lived workspace */
2067 oldcontext = MemoryContextSwitchTo(root->planner_cxt);
2069 cache = (MergeScanSelCache *) palloc(sizeof(MergeScanSelCache));
2070 cache->opfamily = pathkey->pk_opfamily;
2071 cache->collation = pathkey->pk_eclass->ec_collation;
2072 cache->strategy = pathkey->pk_strategy;
2073 cache->nulls_first = pathkey->pk_nulls_first;
2074 cache->leftstartsel = leftstartsel;
2075 cache->leftendsel = leftendsel;
2076 cache->rightstartsel = rightstartsel;
2077 cache->rightendsel = rightendsel;
2079 rinfo->scansel_cache = lappend(rinfo->scansel_cache, cache);
2081 MemoryContextSwitchTo(oldcontext);
2088 * Determines and returns the cost of joining two relations using the
2089 * hash join algorithm.
2091 * 'path' is already filled in except for the cost fields
2092 * 'sjinfo' is extra info about the join for selectivity estimation
2094 * Note: path's hashclauses should be a subset of the joinrestrictinfo list
2097 cost_hashjoin(HashPath *path, PlannerInfo *root, SpecialJoinInfo *sjinfo)
2099 Path *outer_path = path->jpath.outerjoinpath;
2100 Path *inner_path = path->jpath.innerjoinpath;
2101 List *hashclauses = path->path_hashclauses;
2102 Cost startup_cost = 0;
2105 QualCost hash_qual_cost;
2106 QualCost qp_qual_cost;
2107 double hashjointuples;
2108 double outer_path_rows = PATH_ROWS(outer_path);
2109 double inner_path_rows = PATH_ROWS(inner_path);
2110 int num_hashclauses = list_length(hashclauses);
2114 double virtualbuckets;
2115 Selectivity innerbucketsize;
2116 Selectivity outer_match_frac;
2117 Selectivity match_count;
2120 if (!enable_hashjoin)
2121 startup_cost += disable_cost;
2124 * Compute cost of the hashquals and qpquals (other restriction clauses)
2127 cost_qual_eval(&hash_qual_cost, hashclauses, root);
2128 cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
2129 qp_qual_cost.startup -= hash_qual_cost.startup;
2130 qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
2132 /* cost of source data */
2133 startup_cost += outer_path->startup_cost;
2134 run_cost += outer_path->total_cost - outer_path->startup_cost;
2135 startup_cost += inner_path->total_cost;
2138 * Cost of computing hash function: must do it once per input tuple. We
2139 * charge one cpu_operator_cost for each column's hash function. Also,
2140 * tack on one cpu_tuple_cost per inner row, to model the costs of
2141 * inserting the row into the hashtable.
2143 * XXX when a hashclause is more complex than a single operator, we really
2144 * should charge the extra eval costs of the left or right side, as
2145 * appropriate, here. This seems more work than it's worth at the moment.
2147 startup_cost += (cpu_operator_cost * num_hashclauses + cpu_tuple_cost)
2149 run_cost += cpu_operator_cost * num_hashclauses * outer_path_rows;
2152 * Get hash table size that executor would use for inner relation.
2154 * XXX for the moment, always assume that skew optimization will be
2155 * performed. As long as SKEW_WORK_MEM_PERCENT is small, it's not worth
2156 * trying to determine that for sure.
2158 * XXX at some point it might be interesting to try to account for skew
2159 * optimization in the cost estimate, but for now, we don't.
2161 ExecChooseHashTableSize(inner_path_rows,
2162 inner_path->parent->width,
2167 virtualbuckets = (double) numbuckets *(double) numbatches;
2169 /* mark the path with estimated # of batches */
2170 path->num_batches = numbatches;
2173 * Determine bucketsize fraction for inner relation. We use the smallest
2174 * bucketsize estimated for any individual hashclause; this is undoubtedly
2177 * BUT: if inner relation has been unique-ified, we can assume it's good
2178 * for hashing. This is important both because it's the right answer, and
2179 * because we avoid contaminating the cache with a value that's wrong for
2180 * non-unique-ified paths.
2182 if (IsA(inner_path, UniquePath))
2183 innerbucketsize = 1.0 / virtualbuckets;
2186 innerbucketsize = 1.0;
2187 foreach(hcl, hashclauses)
2189 RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(hcl);
2190 Selectivity thisbucketsize;
2192 Assert(IsA(restrictinfo, RestrictInfo));
2195 * First we have to figure out which side of the hashjoin clause
2196 * is the inner side.
2198 * Since we tend to visit the same clauses over and over when
2199 * planning a large query, we cache the bucketsize estimate in the
2200 * RestrictInfo node to avoid repeated lookups of statistics.
2202 if (bms_is_subset(restrictinfo->right_relids,
2203 inner_path->parent->relids))
2205 /* righthand side is inner */
2206 thisbucketsize = restrictinfo->right_bucketsize;
2207 if (thisbucketsize < 0)
2209 /* not cached yet */
2211 estimate_hash_bucketsize(root,
2212 get_rightop(restrictinfo->clause),
2214 restrictinfo->right_bucketsize = thisbucketsize;
2219 Assert(bms_is_subset(restrictinfo->left_relids,
2220 inner_path->parent->relids));
2221 /* lefthand side is inner */
2222 thisbucketsize = restrictinfo->left_bucketsize;
2223 if (thisbucketsize < 0)
2225 /* not cached yet */
2227 estimate_hash_bucketsize(root,
2228 get_leftop(restrictinfo->clause),
2230 restrictinfo->left_bucketsize = thisbucketsize;
2234 if (innerbucketsize > thisbucketsize)
2235 innerbucketsize = thisbucketsize;
2240 * If inner relation is too big then we will need to "batch" the join,
2241 * which implies writing and reading most of the tuples to disk an extra
2242 * time. Charge seq_page_cost per page, since the I/O should be nice and
2243 * sequential. Writing the inner rel counts as startup cost, all the rest
2248 double outerpages = page_size(outer_path_rows,
2249 outer_path->parent->width);
2250 double innerpages = page_size(inner_path_rows,
2251 inner_path->parent->width);
2253 startup_cost += seq_page_cost * innerpages;
2254 run_cost += seq_page_cost * (innerpages + 2 * outerpages);
2259 if (adjust_semi_join(root, &path->jpath, sjinfo,
2264 double outer_matched_rows;
2265 Selectivity inner_scan_frac;
2268 * SEMI or ANTI join: executor will stop after first match.
2270 * For an outer-rel row that has at least one match, we can expect the
2271 * bucket scan to stop after a fraction 1/(match_count+1) of the
2272 * bucket's rows, if the matches are evenly distributed. Since they
2273 * probably aren't quite evenly distributed, we apply a fuzz factor of
2274 * 2.0 to that fraction. (If we used a larger fuzz factor, we'd have
2275 * to clamp inner_scan_frac to at most 1.0; but since match_count is
2276 * at least 1, no such clamp is needed now.)
2278 outer_matched_rows = rint(outer_path_rows * outer_match_frac);
2279 inner_scan_frac = 2.0 / (match_count + 1.0);
2281 startup_cost += hash_qual_cost.startup;
2282 run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
2283 clamp_row_est(inner_path_rows * innerbucketsize * inner_scan_frac) * 0.5;
2286 * For unmatched outer-rel rows, the picture is quite a lot different.
2287 * In the first place, there is no reason to assume that these rows
2288 * preferentially hit heavily-populated buckets; instead assume they
2289 * are uncorrelated with the inner distribution and so they see an
2290 * average bucket size of inner_path_rows / virtualbuckets. In the
2291 * second place, it seems likely that they will have few if any exact
2292 * hash-code matches and so very few of the tuples in the bucket will
2293 * actually require eval of the hash quals. We don't have any good
2294 * way to estimate how many will, but for the moment assume that the
2295 * effective cost per bucket entry is one-tenth what it is for
2298 run_cost += hash_qual_cost.per_tuple *
2299 (outer_path_rows - outer_matched_rows) *
2300 clamp_row_est(inner_path_rows / virtualbuckets) * 0.05;
2302 /* Get # of tuples that will pass the basic join */
2303 if (path->jpath.jointype == JOIN_SEMI)
2304 hashjointuples = outer_matched_rows;
2306 hashjointuples = outer_path_rows - outer_matched_rows;
2311 * The number of tuple comparisons needed is the number of outer
2312 * tuples times the typical number of tuples in a hash bucket, which
2313 * is the inner relation size times its bucketsize fraction. At each
2314 * one, we need to evaluate the hashjoin quals. But actually,
2315 * charging the full qual eval cost at each tuple is pessimistic,
2316 * since we don't evaluate the quals unless the hash values match
2317 * exactly. For lack of a better idea, halve the cost estimate to
2320 startup_cost += hash_qual_cost.startup;
2321 run_cost += hash_qual_cost.per_tuple * outer_path_rows *
2322 clamp_row_est(inner_path_rows * innerbucketsize) * 0.5;
2325 * Get approx # tuples passing the hashquals. We use
2326 * approx_tuple_count here because we need an estimate done with
2327 * JOIN_INNER semantics.
2329 hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
2333 * For each tuple that gets through the hashjoin proper, we charge
2334 * cpu_tuple_cost plus the cost of evaluating additional restriction
2335 * clauses that are to be applied at the join. (This is pessimistic since
2336 * not all of the quals may get evaluated at each tuple.)
2338 startup_cost += qp_qual_cost.startup;
2339 cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
2340 run_cost += cpu_per_tuple * hashjointuples;
2342 path->jpath.path.startup_cost = startup_cost;
2343 path->jpath.path.total_cost = startup_cost + run_cost;
2349 * Figure the costs for a SubPlan (or initplan).
2351 * Note: we could dig the subplan's Plan out of the root list, but in practice
2352 * all callers have it handy already, so we make them pass it.
2355 cost_subplan(PlannerInfo *root, SubPlan *subplan, Plan *plan)
2359 /* Figure any cost for evaluating the testexpr */
2360 cost_qual_eval(&sp_cost,
2361 make_ands_implicit((Expr *) subplan->testexpr),
2364 if (subplan->useHashTable)
2367 * If we are using a hash table for the subquery outputs, then the
2368 * cost of evaluating the query is a one-time cost. We charge one
2369 * cpu_operator_cost per tuple for the work of loading the hashtable,
2372 sp_cost.startup += plan->total_cost +
2373 cpu_operator_cost * plan->plan_rows;
2376 * The per-tuple costs include the cost of evaluating the lefthand
2377 * expressions, plus the cost of probing the hashtable. We already
2378 * accounted for the lefthand expressions as part of the testexpr, and
2379 * will also have counted one cpu_operator_cost for each comparison
2380 * operator. That is probably too low for the probing cost, but it's
2381 * hard to make a better estimate, so live with it for now.
2387 * Otherwise we will be rescanning the subplan output on each
2388 * evaluation. We need to estimate how much of the output we will
2389 * actually need to scan. NOTE: this logic should agree with the
2390 * tuple_fraction estimates used by make_subplan() in
2393 Cost plan_run_cost = plan->total_cost - plan->startup_cost;
2395 if (subplan->subLinkType == EXISTS_SUBLINK)
2397 /* we only need to fetch 1 tuple */
2398 sp_cost.per_tuple += plan_run_cost / plan->plan_rows;
2400 else if (subplan->subLinkType == ALL_SUBLINK ||
2401 subplan->subLinkType == ANY_SUBLINK)
2403 /* assume we need 50% of the tuples */
2404 sp_cost.per_tuple += 0.50 * plan_run_cost;
2405 /* also charge a cpu_operator_cost per row examined */
2406 sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
2410 /* assume we need all tuples */
2411 sp_cost.per_tuple += plan_run_cost;
2415 * Also account for subplan's startup cost. If the subplan is
2416 * uncorrelated or undirect correlated, AND its topmost node is one
2417 * that materializes its output, assume that we'll only need to pay
2418 * its startup cost once; otherwise assume we pay the startup cost
2421 if (subplan->parParam == NIL &&
2422 ExecMaterializesOutput(nodeTag(plan)))
2423 sp_cost.startup += plan->startup_cost;
2425 sp_cost.per_tuple += plan->startup_cost;
2428 subplan->startup_cost = sp_cost.startup;
2429 subplan->per_call_cost = sp_cost.per_tuple;
2435 * Given a finished Path, estimate the costs of rescanning it after
2436 * having done so the first time. For some Path types a rescan is
2437 * cheaper than an original scan (if no parameters change), and this
2438 * function embodies knowledge about that. The default is to return
2439 * the same costs stored in the Path. (Note that the cost estimates
2440 * actually stored in Paths are always for first scans.)
2442 * This function is not currently intended to model effects such as rescans
2443 * being cheaper due to disk block caching; what we are concerned with is
2444 * plan types wherein the executor caches results explicitly, or doesn't
2445 * redo startup calculations, etc.
2448 cost_rescan(PlannerInfo *root, Path *path,
2449 Cost *rescan_startup_cost, /* output parameters */
2450 Cost *rescan_total_cost)
2452 switch (path->pathtype)
2454 case T_FunctionScan:
2457 * Currently, nodeFunctionscan.c always executes the function to
2458 * completion before returning any rows, and caches the results in
2459 * a tuplestore. So the function eval cost is all startup cost
2460 * and isn't paid over again on rescans. However, all run costs
2461 * will be paid over again.
2463 *rescan_startup_cost = 0;
2464 *rescan_total_cost = path->total_cost - path->startup_cost;
2469 * Assume that all of the startup cost represents hash table
2470 * building, which we won't have to do over.
2472 *rescan_startup_cost = 0;
2473 *rescan_total_cost = path->total_cost - path->startup_cost;
2476 case T_WorkTableScan:
2479 * These plan types materialize their final result in a
2480 * tuplestore or tuplesort object. So the rescan cost is only
2481 * cpu_tuple_cost per tuple, unless the result is large enough
2484 Cost run_cost = cpu_tuple_cost * path->parent->rows;
2485 double nbytes = relation_byte_size(path->parent->rows,
2486 path->parent->width);
2487 long work_mem_bytes = work_mem * 1024L;
2489 if (nbytes > work_mem_bytes)
2491 /* It will spill, so account for re-read cost */
2492 double npages = ceil(nbytes / BLCKSZ);
2494 run_cost += seq_page_cost * npages;
2496 *rescan_startup_cost = 0;
2497 *rescan_total_cost = run_cost;
2504 * These plan types not only materialize their results, but do
2505 * not implement qual filtering or projection. So they are
2506 * even cheaper to rescan than the ones above. We charge only
2507 * cpu_operator_cost per tuple. (Note: keep that in sync with
2508 * the run_cost charge in cost_sort, and also see comments in
2509 * cost_material before you change it.)
2511 Cost run_cost = cpu_operator_cost * path->parent->rows;
2512 double nbytes = relation_byte_size(path->parent->rows,
2513 path->parent->width);
2514 long work_mem_bytes = work_mem * 1024L;
2516 if (nbytes > work_mem_bytes)
2518 /* It will spill, so account for re-read cost */
2519 double npages = ceil(nbytes / BLCKSZ);
2521 run_cost += seq_page_cost * npages;
2523 *rescan_startup_cost = 0;
2524 *rescan_total_cost = run_cost;
2528 *rescan_startup_cost = path->startup_cost;
2529 *rescan_total_cost = path->total_cost;
2537 * Estimate the CPU costs of evaluating a WHERE clause.
2538 * The input can be either an implicitly-ANDed list of boolean
2539 * expressions, or a list of RestrictInfo nodes. (The latter is
2540 * preferred since it allows caching of the results.)
2541 * The result includes both a one-time (startup) component,
2542 * and a per-evaluation component.
2545 cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
2547 cost_qual_eval_context context;
2550 context.root = root;
2551 context.total.startup = 0;
2552 context.total.per_tuple = 0;
2554 /* We don't charge any cost for the implicit ANDing at top level ... */
2558 Node *qual = (Node *) lfirst(l);
2560 cost_qual_eval_walker(qual, &context);
2563 *cost = context.total;
2567 * cost_qual_eval_node
2568 * As above, for a single RestrictInfo or expression.
2571 cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
2573 cost_qual_eval_context context;
2575 context.root = root;
2576 context.total.startup = 0;
2577 context.total.per_tuple = 0;
2579 cost_qual_eval_walker(qual, &context);
2581 *cost = context.total;
2585 cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
2591 * RestrictInfo nodes contain an eval_cost field reserved for this
2592 * routine's use, so that it's not necessary to evaluate the qual clause's
2593 * cost more than once. If the clause's cost hasn't been computed yet,
2594 * the field's startup value will contain -1.
2596 if (IsA(node, RestrictInfo))
2598 RestrictInfo *rinfo = (RestrictInfo *) node;
2600 if (rinfo->eval_cost.startup < 0)
2602 cost_qual_eval_context locContext;
2604 locContext.root = context->root;
2605 locContext.total.startup = 0;
2606 locContext.total.per_tuple = 0;
2609 * For an OR clause, recurse into the marked-up tree so that we
2610 * set the eval_cost for contained RestrictInfos too.
2612 if (rinfo->orclause)
2613 cost_qual_eval_walker((Node *) rinfo->orclause, &locContext);
2615 cost_qual_eval_walker((Node *) rinfo->clause, &locContext);
2618 * If the RestrictInfo is marked pseudoconstant, it will be tested
2619 * only once, so treat its cost as all startup cost.
2621 if (rinfo->pseudoconstant)
2623 /* count one execution during startup */
2624 locContext.total.startup += locContext.total.per_tuple;
2625 locContext.total.per_tuple = 0;
2627 rinfo->eval_cost = locContext.total;
2629 context->total.startup += rinfo->eval_cost.startup;
2630 context->total.per_tuple += rinfo->eval_cost.per_tuple;
2631 /* do NOT recurse into children */
2636 * For each operator or function node in the given tree, we charge the
2637 * estimated execution cost given by pg_proc.procost (remember to multiply
2638 * this by cpu_operator_cost).
2640 * Vars and Consts are charged zero, and so are boolean operators (AND,
2641 * OR, NOT). Simplistic, but a lot better than no model at all.
2643 * Note that Aggref and WindowFunc nodes are (and should be) treated like
2644 * Vars --- whatever execution cost they have is absorbed into
2645 * plan-node-specific costing. As far as expression evaluation is
2646 * concerned they're just like Vars.
2648 * Should we try to account for the possibility of short-circuit
2649 * evaluation of AND/OR? Probably *not*, because that would make the
2650 * results depend on the clause ordering, and we are not in any position
2651 * to expect that the current ordering of the clauses is the one that's
2652 * going to end up being used. (Is it worth applying order_qual_clauses
2653 * much earlier in the planning process to fix this?)
2655 if (IsA(node, FuncExpr))
2657 context->total.per_tuple +=
2658 get_func_cost(((FuncExpr *) node)->funcid) * cpu_operator_cost;
2660 else if (IsA(node, OpExpr) ||
2661 IsA(node, DistinctExpr) ||
2662 IsA(node, NullIfExpr))
2664 /* rely on struct equivalence to treat these all alike */
2665 set_opfuncid((OpExpr *) node);
2666 context->total.per_tuple +=
2667 get_func_cost(((OpExpr *) node)->opfuncid) * cpu_operator_cost;
2669 else if (IsA(node, ScalarArrayOpExpr))
2672 * Estimate that the operator will be applied to about half of the
2673 * array elements before the answer is determined.
2675 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
2676 Node *arraynode = (Node *) lsecond(saop->args);
2678 set_sa_opfuncid(saop);
2679 context->total.per_tuple += get_func_cost(saop->opfuncid) *
2680 cpu_operator_cost * estimate_array_length(arraynode) * 0.5;
2682 else if (IsA(node, CoerceViaIO))
2684 CoerceViaIO *iocoerce = (CoerceViaIO *) node;
2689 /* check the result type's input function */
2690 getTypeInputInfo(iocoerce->resulttype,
2691 &iofunc, &typioparam);
2692 context->total.per_tuple += get_func_cost(iofunc) * cpu_operator_cost;
2693 /* check the input type's output function */
2694 getTypeOutputInfo(exprType((Node *) iocoerce->arg),
2695 &iofunc, &typisvarlena);
2696 context->total.per_tuple += get_func_cost(iofunc) * cpu_operator_cost;
2698 else if (IsA(node, ArrayCoerceExpr))
2700 ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
2701 Node *arraynode = (Node *) acoerce->arg;
2703 if (OidIsValid(acoerce->elemfuncid))
2704 context->total.per_tuple += get_func_cost(acoerce->elemfuncid) *
2705 cpu_operator_cost * estimate_array_length(arraynode);
2707 else if (IsA(node, RowCompareExpr))
2709 /* Conservatively assume we will check all the columns */
2710 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
2713 foreach(lc, rcexpr->opnos)
2715 Oid opid = lfirst_oid(lc);
2717 context->total.per_tuple += get_func_cost(get_opcode(opid)) *
2721 else if (IsA(node, CurrentOfExpr))
2723 /* Report high cost to prevent selection of anything but TID scan */
2724 context->total.startup += disable_cost;
2726 else if (IsA(node, SubLink))
2728 /* This routine should not be applied to un-planned expressions */
2729 elog(ERROR, "cannot handle unplanned sub-select");
2731 else if (IsA(node, SubPlan))
2734 * A subplan node in an expression typically indicates that the
2735 * subplan will be executed on each evaluation, so charge accordingly.
2736 * (Sub-selects that can be executed as InitPlans have already been
2737 * removed from the expression.)
2739 SubPlan *subplan = (SubPlan *) node;
2741 context->total.startup += subplan->startup_cost;
2742 context->total.per_tuple += subplan->per_call_cost;
2745 * We don't want to recurse into the testexpr, because it was already
2746 * counted in the SubPlan node's costs. So we're done.
2750 else if (IsA(node, AlternativeSubPlan))
2753 * Arbitrarily use the first alternative plan for costing. (We should
2754 * certainly only include one alternative, and we don't yet have
2755 * enough information to know which one the executor is most likely to
2758 AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
2760 return cost_qual_eval_walker((Node *) linitial(asplan->subplans),
2764 /* recurse into children */
2765 return expression_tree_walker(node, cost_qual_eval_walker,
2772 * Estimate how much of the inner input a SEMI or ANTI join
2773 * can be expected to scan.
2775 * In a hash or nestloop SEMI/ANTI join, the executor will stop scanning
2776 * inner rows as soon as it finds a match to the current outer row.
2777 * We should therefore adjust some of the cost components for this effect.
2778 * This function computes some estimates needed for these adjustments.
2780 * 'path' is already filled in except for the cost fields
2781 * 'sjinfo' is extra info about the join for selectivity estimation
2783 * Returns TRUE if this is a SEMI or ANTI join, FALSE if not.
2785 * Output parameters (set only in TRUE-result case):
2786 * *outer_match_frac is set to the fraction of the outer tuples that are
2787 * expected to have at least one match.
2788 * *match_count is set to the average number of matches expected for
2789 * outer tuples that have at least one match.
2790 * *indexed_join_quals is set to TRUE if all the joinquals are used as
2791 * inner index quals, FALSE if not.
2793 * indexed_join_quals can be passed as NULL if that information is not
2794 * relevant (it is only useful for the nestloop case).
2797 adjust_semi_join(PlannerInfo *root, JoinPath *path, SpecialJoinInfo *sjinfo,
2798 Selectivity *outer_match_frac,
2799 Selectivity *match_count,
2800 bool *indexed_join_quals)
2802 JoinType jointype = path->jointype;
2805 Selectivity avgmatch;
2806 SpecialJoinInfo norm_sjinfo;
2810 /* Fall out if it's not JOIN_SEMI or JOIN_ANTI */
2811 if (jointype != JOIN_SEMI && jointype != JOIN_ANTI)
2815 * Note: it's annoying to repeat this selectivity estimation on each call,
2816 * when the joinclause list will be the same for all path pairs
2817 * implementing a given join. clausesel.c will save us from the worst
2818 * effects of this by caching at the RestrictInfo level; but perhaps it'd
2819 * be worth finding a way to cache the results at a higher level.
2823 * In an ANTI join, we must ignore clauses that are "pushed down", since
2824 * those won't affect the match logic. In a SEMI join, we do not
2825 * distinguish joinquals from "pushed down" quals, so just use the whole
2826 * restrictinfo list.
2828 if (jointype == JOIN_ANTI)
2831 foreach(l, path->joinrestrictinfo)
2833 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
2835 Assert(IsA(rinfo, RestrictInfo));
2836 if (!rinfo->is_pushed_down)
2837 joinquals = lappend(joinquals, rinfo);
2841 joinquals = path->joinrestrictinfo;
2844 * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
2846 jselec = clauselist_selectivity(root,
2853 * Also get the normal inner-join selectivity of the join clauses.
2855 norm_sjinfo.type = T_SpecialJoinInfo;
2856 norm_sjinfo.min_lefthand = path->outerjoinpath->parent->relids;
2857 norm_sjinfo.min_righthand = path->innerjoinpath->parent->relids;
2858 norm_sjinfo.syn_lefthand = path->outerjoinpath->parent->relids;
2859 norm_sjinfo.syn_righthand = path->innerjoinpath->parent->relids;
2860 norm_sjinfo.jointype = JOIN_INNER;
2861 /* we don't bother trying to make the remaining fields valid */
2862 norm_sjinfo.lhs_strict = false;
2863 norm_sjinfo.delay_upper_joins = false;
2864 norm_sjinfo.join_quals = NIL;
2866 nselec = clauselist_selectivity(root,
2872 /* Avoid leaking a lot of ListCells */
2873 if (jointype == JOIN_ANTI)
2874 list_free(joinquals);
2877 * jselec can be interpreted as the fraction of outer-rel rows that have
2878 * any matches (this is true for both SEMI and ANTI cases). And nselec is
2879 * the fraction of the Cartesian product that matches. So, the average
2880 * number of matches for each outer-rel row that has at least one match is
2881 * nselec * inner_rows / jselec.
2883 * Note: it is correct to use the inner rel's "rows" count here, not
2884 * PATH_ROWS(), even if the inner path under consideration is an inner
2885 * indexscan. This is because we have included all the join clauses in
2886 * the selectivity estimate, even ones used in an inner indexscan.
2888 if (jselec > 0) /* protect against zero divide */
2890 avgmatch = nselec * path->innerjoinpath->parent->rows / jselec;
2891 /* Clamp to sane range */
2892 avgmatch = Max(1.0, avgmatch);
2897 *outer_match_frac = jselec;
2898 *match_count = avgmatch;
2901 * If requested, check whether the inner path uses all the joinquals as
2902 * indexquals. (If that's true, we can assume that an unmatched outer
2903 * tuple is cheap to process, whereas otherwise it's probably expensive.)
2905 if (indexed_join_quals)
2907 if (path->joinrestrictinfo != NIL)
2911 nrclauses = select_nonredundant_join_clauses(root,
2912 path->joinrestrictinfo,
2913 path->innerjoinpath);
2914 *indexed_join_quals = (nrclauses == NIL);
2918 /* a clauseless join does NOT qualify */
2919 *indexed_join_quals = false;
2928 * approx_tuple_count
2929 * Quick-and-dirty estimation of the number of join rows passing
2930 * a set of qual conditions.
2932 * The quals can be either an implicitly-ANDed list of boolean expressions,
2933 * or a list of RestrictInfo nodes (typically the latter).
2935 * We intentionally compute the selectivity under JOIN_INNER rules, even
2936 * if it's some type of outer join. This is appropriate because we are
2937 * trying to figure out how many tuples pass the initial merge or hash
2940 * This is quick-and-dirty because we bypass clauselist_selectivity, and
2941 * simply multiply the independent clause selectivities together. Now
2942 * clauselist_selectivity often can't do any better than that anyhow, but
2943 * for some situations (such as range constraints) it is smarter. However,
2944 * we can't effectively cache the results of clauselist_selectivity, whereas
2945 * the individual clause selectivities can be and are cached.
2947 * Since we are only using the results to estimate how many potential
2948 * output tuples are generated and passed through qpqual checking, it
2949 * seems OK to live with the approximation.
2952 approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
2955 double outer_tuples = path->outerjoinpath->parent->rows;
2956 double inner_tuples = path->innerjoinpath->parent->rows;
2957 SpecialJoinInfo sjinfo;
2958 Selectivity selec = 1.0;
2962 * Make up a SpecialJoinInfo for JOIN_INNER semantics.
2964 sjinfo.type = T_SpecialJoinInfo;
2965 sjinfo.min_lefthand = path->outerjoinpath->parent->relids;
2966 sjinfo.min_righthand = path->innerjoinpath->parent->relids;
2967 sjinfo.syn_lefthand = path->outerjoinpath->parent->relids;
2968 sjinfo.syn_righthand = path->innerjoinpath->parent->relids;
2969 sjinfo.jointype = JOIN_INNER;
2970 /* we don't bother trying to make the remaining fields valid */
2971 sjinfo.lhs_strict = false;
2972 sjinfo.delay_upper_joins = false;
2973 sjinfo.join_quals = NIL;
2975 /* Get the approximate selectivity */
2978 Node *qual = (Node *) lfirst(l);
2980 /* Note that clause_selectivity will be able to cache its result */
2981 selec *= clause_selectivity(root, qual, 0, JOIN_INNER, &sjinfo);
2984 /* Apply it to the input relation sizes */
2985 tuples = selec * outer_tuples * inner_tuples;
2987 return clamp_row_est(tuples);
2992 * set_baserel_size_estimates
2993 * Set the size estimates for the given base relation.
2995 * The rel's targetlist and restrictinfo list must have been constructed
2996 * already, and rel->tuples must be set.
2998 * We set the following fields of the rel node:
2999 * rows: the estimated number of output tuples (after applying
3000 * restriction clauses).
3001 * width: the estimated average output tuple width in bytes.
3002 * baserestrictcost: estimated cost of evaluating baserestrictinfo clauses.
3005 set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3009 /* Should only be applied to base relations */
3010 Assert(rel->relid > 0);
3012 nrows = rel->tuples *
3013 clauselist_selectivity(root,
3014 rel->baserestrictinfo,
3019 rel->rows = clamp_row_est(nrows);
3021 cost_qual_eval(&rel->baserestrictcost, rel->baserestrictinfo, root);
3023 set_rel_width(root, rel);
3027 * set_joinrel_size_estimates
3028 * Set the size estimates for the given join relation.
3030 * The rel's targetlist must have been constructed already, and a
3031 * restriction clause list that matches the given component rels must
3034 * Since there is more than one way to make a joinrel for more than two
3035 * base relations, the results we get here could depend on which component
3036 * rel pair is provided. In theory we should get the same answers no matter
3037 * which pair is provided; in practice, since the selectivity estimation
3038 * routines don't handle all cases equally well, we might not. But there's
3039 * not much to be done about it. (Would it make sense to repeat the
3040 * calculations for each pair of input rels that's encountered, and somehow
3041 * average the results? Probably way more trouble than it's worth.)
3043 * We set only the rows field here. The width field was already set by
3044 * build_joinrel_tlist, and baserestrictcost is not used for join rels.
3047 set_joinrel_size_estimates(PlannerInfo *root, RelOptInfo *rel,
3048 RelOptInfo *outer_rel,
3049 RelOptInfo *inner_rel,
3050 SpecialJoinInfo *sjinfo,
3053 JoinType jointype = sjinfo->jointype;
3059 * Compute joinclause selectivity. Note that we are only considering
3060 * clauses that become restriction clauses at this join level; we are not
3061 * double-counting them because they were not considered in estimating the
3062 * sizes of the component rels.
3064 * For an outer join, we have to distinguish the selectivity of the join's
3065 * own clauses (JOIN/ON conditions) from any clauses that were "pushed
3066 * down". For inner joins we just count them all as joinclauses.
3068 if (IS_OUTER_JOIN(jointype))
3070 List *joinquals = NIL;
3071 List *pushedquals = NIL;
3074 /* Grovel through the clauses to separate into two lists */
3075 foreach(l, restrictlist)
3077 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
3079 Assert(IsA(rinfo, RestrictInfo));
3080 if (rinfo->is_pushed_down)
3081 pushedquals = lappend(pushedquals, rinfo);
3083 joinquals = lappend(joinquals, rinfo);
3086 /* Get the separate selectivities */
3087 jselec = clauselist_selectivity(root,
3092 pselec = clauselist_selectivity(root,
3098 /* Avoid leaking a lot of ListCells */
3099 list_free(joinquals);
3100 list_free(pushedquals);
3104 jselec = clauselist_selectivity(root,
3109 pselec = 0.0; /* not used, keep compiler quiet */
3113 * Basically, we multiply size of Cartesian product by selectivity.
3115 * If we are doing an outer join, take that into account: the joinqual
3116 * selectivity has to be clamped using the knowledge that the output must
3117 * be at least as large as the non-nullable input. However, any
3118 * pushed-down quals are applied after the outer join, so their
3119 * selectivity applies fully.
3121 * For JOIN_SEMI and JOIN_ANTI, the selectivity is defined as the fraction
3122 * of LHS rows that have matches, and we apply that straightforwardly.
3127 nrows = outer_rel->rows * inner_rel->rows * jselec;
3130 nrows = outer_rel->rows * inner_rel->rows * jselec;
3131 if (nrows < outer_rel->rows)
3132 nrows = outer_rel->rows;
3136 nrows = outer_rel->rows * inner_rel->rows * jselec;
3137 if (nrows < outer_rel->rows)
3138 nrows = outer_rel->rows;
3139 if (nrows < inner_rel->rows)
3140 nrows = inner_rel->rows;
3144 nrows = outer_rel->rows * jselec;
3145 /* pselec not used */
3148 nrows = outer_rel->rows * (1.0 - jselec);
3152 /* other values not expected here */
3153 elog(ERROR, "unrecognized join type: %d", (int) jointype);
3154 nrows = 0; /* keep compiler quiet */
3158 rel->rows = clamp_row_est(nrows);
3162 * set_subquery_size_estimates
3163 * Set the size estimates for a base relation that is a subquery.
3165 * The rel's targetlist and restrictinfo list must have been constructed
3166 * already, and the plan for the subquery must have been completed.
3167 * We look at the subquery's plan and PlannerInfo to extract data.
3169 * We set the same fields as set_baserel_size_estimates.
3172 set_subquery_size_estimates(PlannerInfo *root, RelOptInfo *rel,
3173 PlannerInfo *subroot)
3178 /* Should only be applied to base relations that are subqueries */
3179 Assert(rel->relid > 0);
3180 rte = planner_rt_fetch(rel->relid, root);
3181 Assert(rte->rtekind == RTE_SUBQUERY);
3183 /* Copy raw number of output rows from subplan */
3184 rel->tuples = rel->subplan->plan_rows;
3187 * Compute per-output-column width estimates by examining the subquery's
3188 * targetlist. For any output that is a plain Var, get the width estimate
3189 * that was made while planning the subquery. Otherwise, fall back on a
3190 * datatype-based estimate.
3192 foreach(lc, subroot->parse->targetList)
3194 TargetEntry *te = (TargetEntry *) lfirst(lc);
3195 Node *texpr = (Node *) te->expr;
3198 Assert(IsA(te, TargetEntry));
3199 /* junk columns aren't visible to upper query */
3204 * XXX This currently doesn't work for subqueries containing set
3205 * operations, because the Vars in their tlists are bogus references
3206 * to the first leaf subquery, which wouldn't give the right answer
3207 * even if we could still get to its PlannerInfo. So fall back on
3208 * datatype in that case.
3210 if (IsA(texpr, Var) &&
3211 subroot->parse->setOperations == NULL)
3213 Var *var = (Var *) texpr;
3214 RelOptInfo *subrel = find_base_rel(subroot, var->varno);
3216 item_width = subrel->attr_widths[var->varattno - subrel->min_attr];
3220 item_width = get_typavgwidth(exprType(texpr), exprTypmod(texpr));
3222 Assert(item_width > 0);
3223 Assert(te->resno >= rel->min_attr && te->resno <= rel->max_attr);
3224 rel->attr_widths[te->resno - rel->min_attr] = item_width;
3227 /* Now estimate number of output rows, etc */
3228 set_baserel_size_estimates(root, rel);
3232 * set_function_size_estimates
3233 * Set the size estimates for a base relation that is a function call.
3235 * The rel's targetlist and restrictinfo list must have been constructed
3238 * We set the same fields as set_baserel_size_estimates.
3241 set_function_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3245 /* Should only be applied to base relations that are functions */
3246 Assert(rel->relid > 0);
3247 rte = planner_rt_fetch(rel->relid, root);
3248 Assert(rte->rtekind == RTE_FUNCTION);
3250 /* Estimate number of rows the function itself will return */
3251 rel->tuples = clamp_row_est(expression_returns_set_rows(rte->funcexpr));
3253 /* Now estimate number of output rows, etc */
3254 set_baserel_size_estimates(root, rel);
3258 * set_values_size_estimates
3259 * Set the size estimates for a base relation that is a values list.
3261 * The rel's targetlist and restrictinfo list must have been constructed
3264 * We set the same fields as set_baserel_size_estimates.
3267 set_values_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3271 /* Should only be applied to base relations that are values lists */
3272 Assert(rel->relid > 0);
3273 rte = planner_rt_fetch(rel->relid, root);
3274 Assert(rte->rtekind == RTE_VALUES);
3277 * Estimate number of rows the values list will return. We know this
3278 * precisely based on the list length (well, barring set-returning
3279 * functions in list items, but that's a refinement not catered for
3280 * anywhere else either).
3282 rel->tuples = list_length(rte->values_lists);
3284 /* Now estimate number of output rows, etc */
3285 set_baserel_size_estimates(root, rel);
3289 * set_cte_size_estimates
3290 * Set the size estimates for a base relation that is a CTE reference.
3292 * The rel's targetlist and restrictinfo list must have been constructed
3293 * already, and we need the completed plan for the CTE (if a regular CTE)
3294 * or the non-recursive term (if a self-reference).
3296 * We set the same fields as set_baserel_size_estimates.
3299 set_cte_size_estimates(PlannerInfo *root, RelOptInfo *rel, Plan *cteplan)
3303 /* Should only be applied to base relations that are CTE references */
3304 Assert(rel->relid > 0);
3305 rte = planner_rt_fetch(rel->relid, root);
3306 Assert(rte->rtekind == RTE_CTE);
3308 if (rte->self_reference)
3311 * In a self-reference, arbitrarily assume the average worktable size
3312 * is about 10 times the nonrecursive term's size.
3314 rel->tuples = 10 * cteplan->plan_rows;
3318 /* Otherwise just believe the CTE plan's output estimate */
3319 rel->tuples = cteplan->plan_rows;
3322 /* Now estimate number of output rows, etc */
3323 set_baserel_size_estimates(root, rel);
3327 * set_foreign_size_estimates
3328 * Set the size estimates for a base relation that is a foreign table.
3330 * There is not a whole lot that we can do here; the foreign-data wrapper
3331 * is responsible for producing useful estimates. We can do a decent job
3332 * of estimating baserestrictcost, so we set that, and we also set up width
3333 * using what will be purely datatype-driven estimates from the targetlist.
3334 * There is no way to do anything sane with the rows value, so we just put
3335 * a default estimate and hope that the wrapper can improve on it. The
3336 * wrapper's PlanForeignScan function will be called momentarily.
3338 * The rel's targetlist and restrictinfo list must have been constructed
3342 set_foreign_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3344 /* Should only be applied to base relations */
3345 Assert(rel->relid > 0);
3347 rel->rows = 1000; /* entirely bogus default estimate */
3349 cost_qual_eval(&rel->baserestrictcost, rel->baserestrictinfo, root);
3351 set_rel_width(root, rel);
3357 * Set the estimated output width of a base relation.
3359 * The estimated output width is the sum of the per-attribute width estimates
3360 * for the actually-referenced columns, plus any PHVs or other expressions
3361 * that have to be calculated at this relation. This is the amount of data
3362 * we'd need to pass upwards in case of a sort, hash, etc.
3364 * NB: this works best on plain relations because it prefers to look at
3365 * real Vars. For subqueries, set_subquery_size_estimates will already have
3366 * copied up whatever per-column estimates were made within the subquery,
3367 * and for other types of rels there isn't much we can do anyway. We fall
3368 * back on (fairly stupid) datatype-based width estimates if we can't get
3369 * any better number.
3371 * The per-attribute width estimates are cached for possible re-use while
3372 * building join relations.
3375 set_rel_width(PlannerInfo *root, RelOptInfo *rel)
3377 Oid reloid = planner_rt_fetch(rel->relid, root)->relid;
3378 int32 tuple_width = 0;
3379 bool have_wholerow_var = false;
3382 foreach(lc, rel->reltargetlist)
3384 Node *node = (Node *) lfirst(lc);
3388 Var *var = (Var *) node;
3392 Assert(var->varno == rel->relid);
3393 Assert(var->varattno >= rel->min_attr);
3394 Assert(var->varattno <= rel->max_attr);
3396 ndx = var->varattno - rel->min_attr;
3399 * If it's a whole-row Var, we'll deal with it below after we
3400 * have already cached as many attr widths as possible.
3402 if (var->varattno == 0)
3404 have_wholerow_var = true;
3409 * The width may have been cached already (especially if it's
3410 * a subquery), so don't duplicate effort.
3412 if (rel->attr_widths[ndx] > 0)
3414 tuple_width += rel->attr_widths[ndx];
3418 /* Try to get column width from statistics */
3419 if (reloid != InvalidOid && var->varattno > 0)
3421 item_width = get_attavgwidth(reloid, var->varattno);
3424 rel->attr_widths[ndx] = item_width;
3425 tuple_width += item_width;
3431 * Not a plain relation, or can't find statistics for it. Estimate
3432 * using just the type info.
3434 item_width = get_typavgwidth(var->vartype, var->vartypmod);
3435 Assert(item_width > 0);
3436 rel->attr_widths[ndx] = item_width;
3437 tuple_width += item_width;
3439 else if (IsA(node, PlaceHolderVar))
3441 PlaceHolderVar *phv = (PlaceHolderVar *) node;
3442 PlaceHolderInfo *phinfo = find_placeholder_info(root, phv);
3444 tuple_width += phinfo->ph_width;
3449 * We could be looking at an expression pulled up from a subquery,
3450 * or a ROW() representing a whole-row child Var, etc. Do what we
3451 * can using the expression type information.
3455 item_width = get_typavgwidth(exprType(node), exprTypmod(node));
3456 Assert(item_width > 0);
3457 tuple_width += item_width;
3462 * If we have a whole-row reference, estimate its width as the sum of
3463 * per-column widths plus sizeof(HeapTupleHeaderData).
3465 if (have_wholerow_var)
3467 int32 wholerow_width = sizeof(HeapTupleHeaderData);
3469 if (reloid != InvalidOid)
3471 /* Real relation, so estimate true tuple width */
3472 wholerow_width += get_relation_data_width(reloid,
3473 rel->attr_widths - rel->min_attr);
3477 /* Do what we can with info for a phony rel */
3480 for (i = 1; i <= rel->max_attr; i++)
3481 wholerow_width += rel->attr_widths[i - rel->min_attr];
3484 rel->attr_widths[0 - rel->min_attr] = wholerow_width;
3487 * Include the whole-row Var as part of the output tuple. Yes,
3488 * that really is what happens at runtime.
3490 tuple_width += wholerow_width;
3493 Assert(tuple_width >= 0);
3494 rel->width = tuple_width;
3498 * relation_byte_size
3499 * Estimate the storage space in bytes for a given number of tuples
3500 * of a given width (size in bytes).
3503 relation_byte_size(double tuples, int width)
3505 return tuples * (MAXALIGN(width) + MAXALIGN(sizeof(HeapTupleHeaderData)));
3510 * Returns an estimate of the number of pages covered by a given
3511 * number of tuples of a given width (size in bytes).
3514 page_size(double tuples, int width)
3516 return ceil(relation_byte_size(tuples, width) / BLCKSZ);