1 /*-------------------------------------------------------------------------
4 * Routines to compute (and set) relation sizes and path costs
6 * Path costs are measured in arbitrary units established by these basic
9 * seq_page_cost Cost of a sequential page fetch
10 * random_page_cost Cost of a non-sequential page fetch
11 * cpu_tuple_cost Cost of typical CPU time to process a tuple
12 * cpu_index_tuple_cost Cost of typical CPU time to process an index tuple
13 * cpu_operator_cost Cost of CPU time to execute an operator or function
15 * We expect that the kernel will typically do some amount of read-ahead
16 * optimization; this in conjunction with seek costs means that seq_page_cost
17 * is normally considerably less than random_page_cost. (However, if the
18 * database is fully cached in RAM, it is reasonable to set them equal.)
20 * We also use a rough estimate "effective_cache_size" of the number of
21 * disk pages in Postgres + OS-level disk cache. (We can't simply use
22 * NBuffers for this purpose because that would ignore the effects of
23 * the kernel's disk cache.)
25 * Obviously, taking constants for these values is an oversimplification,
26 * but it's tough enough to get any useful estimates even at this level of
27 * detail. Note that all of these parameters are user-settable, in case
28 * the default values are drastically off for a particular platform.
30 * seq_page_cost and random_page_cost can also be overridden for an individual
31 * tablespace, in case some data is on a fast disk and other data is on a slow
32 * disk. Per-tablespace overrides never apply to temporary work files such as
33 * an external sort or a materialize node that overflows work_mem.
35 * We compute two separate costs for each path:
36 * total_cost: total estimated cost to fetch all tuples
37 * startup_cost: cost that is expended before first tuple is fetched
38 * In some scenarios, such as when there is a LIMIT or we are implementing
39 * an EXISTS(...) sub-select, it is not necessary to fetch all tuples of the
40 * path's result. A caller can estimate the cost of fetching a partial
41 * result by interpolating between startup_cost and total_cost. In detail:
42 * actual_cost = startup_cost +
43 * (total_cost - startup_cost) * tuples_to_fetch / path->parent->rows;
44 * Note that a base relation's rows count (and, by extension, plan_rows for
45 * plan nodes below the LIMIT node) are set without regard to any LIMIT, so
46 * that this equation works properly. (Also, these routines guarantee not to
47 * set the rows count to zero, so there will be no zero divide.) The LIMIT is
48 * applied as a top-level plan node.
50 * For largely historical reasons, most of the routines in this module use
51 * the passed result Path only to store their startup_cost and total_cost
52 * results into. All the input data they need is passed as separate
53 * parameters, even though much of it could be extracted from the Path.
54 * An exception is made for the cost_XXXjoin() routines, which expect all
55 * the non-cost fields of the passed XXXPath to be filled in.
58 * Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
59 * Portions Copyright (c) 1994, Regents of the University of California
62 * src/backend/optimizer/path/costsize.c
64 *-------------------------------------------------------------------------
71 #include "executor/executor.h"
72 #include "executor/nodeHash.h"
73 #include "miscadmin.h"
74 #include "nodes/nodeFuncs.h"
75 #include "optimizer/clauses.h"
76 #include "optimizer/cost.h"
77 #include "optimizer/pathnode.h"
78 #include "optimizer/placeholder.h"
79 #include "optimizer/plancat.h"
80 #include "optimizer/planmain.h"
81 #include "optimizer/restrictinfo.h"
82 #include "parser/parsetree.h"
83 #include "utils/lsyscache.h"
84 #include "utils/selfuncs.h"
85 #include "utils/spccache.h"
86 #include "utils/tuplesort.h"
89 #define LOG2(x) (log(x) / 0.693147180559945)
92 * Some Paths return less than the nominal number of rows of their parent
93 * relations; join nodes need to do this to get the correct input count:
95 #define PATH_ROWS(path) \
96 (IsA(path, UniquePath) ? \
97 ((UniquePath *) (path))->rows : \
101 double seq_page_cost = DEFAULT_SEQ_PAGE_COST;
102 double random_page_cost = DEFAULT_RANDOM_PAGE_COST;
103 double cpu_tuple_cost = DEFAULT_CPU_TUPLE_COST;
104 double cpu_index_tuple_cost = DEFAULT_CPU_INDEX_TUPLE_COST;
105 double cpu_operator_cost = DEFAULT_CPU_OPERATOR_COST;
107 int effective_cache_size = DEFAULT_EFFECTIVE_CACHE_SIZE;
109 Cost disable_cost = 1.0e10;
111 bool enable_seqscan = true;
112 bool enable_indexscan = true;
113 bool enable_bitmapscan = true;
114 bool enable_tidscan = true;
115 bool enable_sort = true;
116 bool enable_hashagg = true;
117 bool enable_nestloop = true;
118 bool enable_material = true;
119 bool enable_mergejoin = true;
120 bool enable_hashjoin = true;
126 } cost_qual_eval_context;
128 static MergeScanSelCache *cached_scansel(PlannerInfo *root,
131 static void cost_rescan(PlannerInfo *root, Path *path,
132 Cost *rescan_startup_cost, Cost *rescan_total_cost);
133 static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context);
134 static bool adjust_semi_join(PlannerInfo *root, JoinPath *path,
135 SpecialJoinInfo *sjinfo,
136 Selectivity *outer_match_frac,
137 Selectivity *match_count,
138 bool *indexed_join_quals);
139 static double approx_tuple_count(PlannerInfo *root, JoinPath *path,
141 static void set_rel_width(PlannerInfo *root, RelOptInfo *rel);
142 static double relation_byte_size(double tuples, int width);
143 static double page_size(double tuples, int width);
148 * Force a row-count estimate to a sane value.
151 clamp_row_est(double nrows)
154 * Force estimate to be at least one row, to make explain output look
155 * better and to avoid possible divide-by-zero when interpolating costs.
156 * Make it an integer, too.
169 * Determines and returns the cost of scanning a relation sequentially.
172 cost_seqscan(Path *path, PlannerInfo *root,
175 double spc_seq_page_cost;
176 Cost startup_cost = 0;
180 /* Should only be applied to base relations */
181 Assert(baserel->relid > 0);
182 Assert(baserel->rtekind == RTE_RELATION);
185 startup_cost += disable_cost;
187 /* fetch estimated page cost for tablespace containing table */
188 get_tablespace_page_costs(baserel->reltablespace,
195 run_cost += spc_seq_page_cost * baserel->pages;
198 startup_cost += baserel->baserestrictcost.startup;
199 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
200 run_cost += cpu_per_tuple * baserel->tuples;
202 path->startup_cost = startup_cost;
203 path->total_cost = startup_cost + run_cost;
208 * Determines and returns the cost of scanning a relation using an index.
210 * 'index' is the index to be used
211 * 'indexQuals' is the list of applicable qual clauses (implicit AND semantics)
212 * '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_strategy != ipathkey->pk_strategy ||
1799 opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
1800 elog(ERROR, "left and right pathkeys do not match in mergejoin");
1802 /* Get the selectivity with caching */
1803 cache = cached_scansel(root, firstclause, opathkey);
1805 if (bms_is_subset(firstclause->left_relids,
1806 outer_path->parent->relids))
1808 /* left side of clause is outer */
1809 outerstartsel = cache->leftstartsel;
1810 outerendsel = cache->leftendsel;
1811 innerstartsel = cache->rightstartsel;
1812 innerendsel = cache->rightendsel;
1816 /* left side of clause is inner */
1817 outerstartsel = cache->rightstartsel;
1818 outerendsel = cache->rightendsel;
1819 innerstartsel = cache->leftstartsel;
1820 innerendsel = cache->leftendsel;
1822 if (path->jpath.jointype == JOIN_LEFT ||
1823 path->jpath.jointype == JOIN_ANTI)
1825 outerstartsel = 0.0;
1828 else if (path->jpath.jointype == JOIN_RIGHT)
1830 innerstartsel = 0.0;
1836 /* cope with clauseless or full mergejoin */
1837 outerstartsel = innerstartsel = 0.0;
1838 outerendsel = innerendsel = 1.0;
1842 * Convert selectivities to row counts. We force outer_rows and
1843 * inner_rows to be at least 1, but the skip_rows estimates can be zero.
1845 outer_skip_rows = rint(outer_path_rows * outerstartsel);
1846 inner_skip_rows = rint(inner_path_rows * innerstartsel);
1847 outer_rows = clamp_row_est(outer_path_rows * outerendsel);
1848 inner_rows = clamp_row_est(inner_path_rows * innerendsel);
1850 Assert(outer_skip_rows <= outer_rows);
1851 Assert(inner_skip_rows <= inner_rows);
1854 * Readjust scan selectivities to account for above rounding. This is
1855 * normally an insignificant effect, but when there are only a few rows in
1856 * the inputs, failing to do this makes for a large percentage error.
1858 outerstartsel = outer_skip_rows / outer_path_rows;
1859 innerstartsel = inner_skip_rows / inner_path_rows;
1860 outerendsel = outer_rows / outer_path_rows;
1861 innerendsel = inner_rows / inner_path_rows;
1863 Assert(outerstartsel <= outerendsel);
1864 Assert(innerstartsel <= innerendsel);
1866 /* cost of source data */
1868 if (outersortkeys) /* do we need to sort outer? */
1870 cost_sort(&sort_path,
1873 outer_path->total_cost,
1875 outer_path->parent->width,
1879 startup_cost += sort_path.startup_cost;
1880 startup_cost += (sort_path.total_cost - sort_path.startup_cost)
1882 run_cost += (sort_path.total_cost - sort_path.startup_cost)
1883 * (outerendsel - outerstartsel);
1887 startup_cost += outer_path->startup_cost;
1888 startup_cost += (outer_path->total_cost - outer_path->startup_cost)
1890 run_cost += (outer_path->total_cost - outer_path->startup_cost)
1891 * (outerendsel - outerstartsel);
1894 if (innersortkeys) /* do we need to sort inner? */
1896 cost_sort(&sort_path,
1899 inner_path->total_cost,
1901 inner_path->parent->width,
1905 startup_cost += sort_path.startup_cost;
1906 startup_cost += (sort_path.total_cost - sort_path.startup_cost)
1908 inner_run_cost = (sort_path.total_cost - sort_path.startup_cost)
1909 * (innerendsel - innerstartsel);
1913 startup_cost += inner_path->startup_cost;
1914 startup_cost += (inner_path->total_cost - inner_path->startup_cost)
1916 inner_run_cost = (inner_path->total_cost - inner_path->startup_cost)
1917 * (innerendsel - innerstartsel);
1921 * Decide whether we want to materialize the inner input to shield it from
1922 * mark/restore and performing re-fetches. Our cost model for regular
1923 * re-fetches is that a re-fetch costs the same as an original fetch,
1924 * which is probably an overestimate; but on the other hand we ignore the
1925 * bookkeeping costs of mark/restore. Not clear if it's worth developing
1926 * a more refined model. So we just need to inflate the inner run cost by
1929 bare_inner_cost = inner_run_cost * rescanratio;
1932 * When we interpose a Material node the re-fetch cost is assumed to be
1933 * just cpu_operator_cost per tuple, independently of the underlying
1934 * plan's cost; and we charge an extra cpu_operator_cost per original
1935 * fetch as well. Note that we're assuming the materialize node will
1936 * never spill to disk, since it only has to remember tuples back to the
1937 * last mark. (If there are a huge number of duplicates, our other cost
1938 * factors will make the path so expensive that it probably won't get
1939 * chosen anyway.) So we don't use cost_rescan here.
1941 * Note: keep this estimate in sync with create_mergejoin_plan's labeling
1942 * of the generated Material node.
1944 mat_inner_cost = inner_run_cost +
1945 cpu_operator_cost * inner_path_rows * rescanratio;
1948 * Prefer materializing if it looks cheaper, unless the user has asked to
1949 * suppress materialization.
1951 if (enable_material && mat_inner_cost < bare_inner_cost)
1952 path->materialize_inner = true;
1955 * Even if materializing doesn't look cheaper, we *must* do it if the
1956 * inner path is to be used directly (without sorting) and it doesn't
1957 * support mark/restore.
1959 * Since the inner side must be ordered, and only Sorts and IndexScans can
1960 * create order to begin with, and they both support mark/restore, you
1961 * might think there's no problem --- but you'd be wrong. Nestloop and
1962 * merge joins can *preserve* the order of their inputs, so they can be
1963 * selected as the input of a mergejoin, and they don't support
1964 * mark/restore at present.
1966 * We don't test the value of enable_material here, because
1967 * materialization is required for correctness in this case, and turning
1968 * it off does not entitle us to deliver an invalid plan.
1970 else if (innersortkeys == NIL &&
1971 !ExecSupportsMarkRestore(inner_path->pathtype))
1972 path->materialize_inner = true;
1975 * Also, force materializing if the inner path is to be sorted and the
1976 * sort is expected to spill to disk. This is because the final merge
1977 * pass can be done on-the-fly if it doesn't have to support mark/restore.
1978 * We don't try to adjust the cost estimates for this consideration,
1981 * Since materialization is a performance optimization in this case,
1982 * rather than necessary for correctness, we skip it if enable_material is
1985 else if (enable_material && innersortkeys != NIL &&
1986 relation_byte_size(inner_path_rows, inner_path->parent->width) >
1988 path->materialize_inner = true;
1990 path->materialize_inner = false;
1992 /* Charge the right incremental cost for the chosen case */
1993 if (path->materialize_inner)
1994 run_cost += mat_inner_cost;
1996 run_cost += bare_inner_cost;
2001 * The number of tuple comparisons needed is approximately number of outer
2002 * rows plus number of inner rows plus number of rescanned tuples (can we
2003 * refine this?). At each one, we need to evaluate the mergejoin quals.
2005 startup_cost += merge_qual_cost.startup;
2006 startup_cost += merge_qual_cost.per_tuple *
2007 (outer_skip_rows + inner_skip_rows * rescanratio);
2008 run_cost += merge_qual_cost.per_tuple *
2009 ((outer_rows - outer_skip_rows) +
2010 (inner_rows - inner_skip_rows) * rescanratio);
2013 * For each tuple that gets through the mergejoin proper, we charge
2014 * cpu_tuple_cost plus the cost of evaluating additional restriction
2015 * clauses that are to be applied at the join. (This is pessimistic since
2016 * not all of the quals may get evaluated at each tuple.)
2018 * Note: we could adjust for SEMI/ANTI joins skipping some qual
2019 * evaluations here, but it's probably not worth the trouble.
2021 startup_cost += qp_qual_cost.startup;
2022 cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
2023 run_cost += cpu_per_tuple * mergejointuples;
2025 path->jpath.path.startup_cost = startup_cost;
2026 path->jpath.path.total_cost = startup_cost + run_cost;
2030 * run mergejoinscansel() with caching
2032 static MergeScanSelCache *
2033 cached_scansel(PlannerInfo *root, RestrictInfo *rinfo, PathKey *pathkey)
2035 MergeScanSelCache *cache;
2037 Selectivity leftstartsel,
2041 MemoryContext oldcontext;
2043 /* Do we have this result already? */
2044 foreach(lc, rinfo->scansel_cache)
2046 cache = (MergeScanSelCache *) lfirst(lc);
2047 if (cache->opfamily == pathkey->pk_opfamily &&
2048 cache->strategy == pathkey->pk_strategy &&
2049 cache->nulls_first == pathkey->pk_nulls_first)
2053 /* Nope, do the computation */
2054 mergejoinscansel(root,
2055 (Node *) rinfo->clause,
2056 pathkey->pk_opfamily,
2057 pathkey->pk_strategy,
2058 pathkey->pk_nulls_first,
2064 /* Cache the result in suitably long-lived workspace */
2065 oldcontext = MemoryContextSwitchTo(root->planner_cxt);
2067 cache = (MergeScanSelCache *) palloc(sizeof(MergeScanSelCache));
2068 cache->opfamily = pathkey->pk_opfamily;
2069 cache->strategy = pathkey->pk_strategy;
2070 cache->nulls_first = pathkey->pk_nulls_first;
2071 cache->leftstartsel = leftstartsel;
2072 cache->leftendsel = leftendsel;
2073 cache->rightstartsel = rightstartsel;
2074 cache->rightendsel = rightendsel;
2076 rinfo->scansel_cache = lappend(rinfo->scansel_cache, cache);
2078 MemoryContextSwitchTo(oldcontext);
2085 * Determines and returns the cost of joining two relations using the
2086 * hash join algorithm.
2088 * 'path' is already filled in except for the cost fields
2089 * 'sjinfo' is extra info about the join for selectivity estimation
2091 * Note: path's hashclauses should be a subset of the joinrestrictinfo list
2094 cost_hashjoin(HashPath *path, PlannerInfo *root, SpecialJoinInfo *sjinfo)
2096 Path *outer_path = path->jpath.outerjoinpath;
2097 Path *inner_path = path->jpath.innerjoinpath;
2098 List *hashclauses = path->path_hashclauses;
2099 Cost startup_cost = 0;
2102 QualCost hash_qual_cost;
2103 QualCost qp_qual_cost;
2104 double hashjointuples;
2105 double outer_path_rows = PATH_ROWS(outer_path);
2106 double inner_path_rows = PATH_ROWS(inner_path);
2107 int num_hashclauses = list_length(hashclauses);
2111 double virtualbuckets;
2112 Selectivity innerbucketsize;
2113 Selectivity outer_match_frac;
2114 Selectivity match_count;
2117 if (!enable_hashjoin)
2118 startup_cost += disable_cost;
2121 * Compute cost of the hashquals and qpquals (other restriction clauses)
2124 cost_qual_eval(&hash_qual_cost, hashclauses, root);
2125 cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
2126 qp_qual_cost.startup -= hash_qual_cost.startup;
2127 qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
2129 /* cost of source data */
2130 startup_cost += outer_path->startup_cost;
2131 run_cost += outer_path->total_cost - outer_path->startup_cost;
2132 startup_cost += inner_path->total_cost;
2135 * Cost of computing hash function: must do it once per input tuple. We
2136 * charge one cpu_operator_cost for each column's hash function. Also,
2137 * tack on one cpu_tuple_cost per inner row, to model the costs of
2138 * inserting the row into the hashtable.
2140 * XXX when a hashclause is more complex than a single operator, we really
2141 * should charge the extra eval costs of the left or right side, as
2142 * appropriate, here. This seems more work than it's worth at the moment.
2144 startup_cost += (cpu_operator_cost * num_hashclauses + cpu_tuple_cost)
2146 run_cost += cpu_operator_cost * num_hashclauses * outer_path_rows;
2149 * Get hash table size that executor would use for inner relation.
2151 * XXX for the moment, always assume that skew optimization will be
2152 * performed. As long as SKEW_WORK_MEM_PERCENT is small, it's not worth
2153 * trying to determine that for sure.
2155 * XXX at some point it might be interesting to try to account for skew
2156 * optimization in the cost estimate, but for now, we don't.
2158 ExecChooseHashTableSize(inner_path_rows,
2159 inner_path->parent->width,
2164 virtualbuckets = (double) numbuckets *(double) numbatches;
2166 /* mark the path with estimated # of batches */
2167 path->num_batches = numbatches;
2170 * Determine bucketsize fraction for inner relation. We use the smallest
2171 * bucketsize estimated for any individual hashclause; this is undoubtedly
2174 * BUT: if inner relation has been unique-ified, we can assume it's good
2175 * for hashing. This is important both because it's the right answer, and
2176 * because we avoid contaminating the cache with a value that's wrong for
2177 * non-unique-ified paths.
2179 if (IsA(inner_path, UniquePath))
2180 innerbucketsize = 1.0 / virtualbuckets;
2183 innerbucketsize = 1.0;
2184 foreach(hcl, hashclauses)
2186 RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(hcl);
2187 Selectivity thisbucketsize;
2189 Assert(IsA(restrictinfo, RestrictInfo));
2192 * First we have to figure out which side of the hashjoin clause
2193 * is the inner side.
2195 * Since we tend to visit the same clauses over and over when
2196 * planning a large query, we cache the bucketsize estimate in the
2197 * RestrictInfo node to avoid repeated lookups of statistics.
2199 if (bms_is_subset(restrictinfo->right_relids,
2200 inner_path->parent->relids))
2202 /* righthand side is inner */
2203 thisbucketsize = restrictinfo->right_bucketsize;
2204 if (thisbucketsize < 0)
2206 /* not cached yet */
2208 estimate_hash_bucketsize(root,
2209 get_rightop(restrictinfo->clause),
2211 restrictinfo->right_bucketsize = thisbucketsize;
2216 Assert(bms_is_subset(restrictinfo->left_relids,
2217 inner_path->parent->relids));
2218 /* lefthand side is inner */
2219 thisbucketsize = restrictinfo->left_bucketsize;
2220 if (thisbucketsize < 0)
2222 /* not cached yet */
2224 estimate_hash_bucketsize(root,
2225 get_leftop(restrictinfo->clause),
2227 restrictinfo->left_bucketsize = thisbucketsize;
2231 if (innerbucketsize > thisbucketsize)
2232 innerbucketsize = thisbucketsize;
2237 * If inner relation is too big then we will need to "batch" the join,
2238 * which implies writing and reading most of the tuples to disk an extra
2239 * time. Charge seq_page_cost per page, since the I/O should be nice and
2240 * sequential. Writing the inner rel counts as startup cost, all the rest
2245 double outerpages = page_size(outer_path_rows,
2246 outer_path->parent->width);
2247 double innerpages = page_size(inner_path_rows,
2248 inner_path->parent->width);
2250 startup_cost += seq_page_cost * innerpages;
2251 run_cost += seq_page_cost * (innerpages + 2 * outerpages);
2256 if (adjust_semi_join(root, &path->jpath, sjinfo,
2261 double outer_matched_rows;
2262 Selectivity inner_scan_frac;
2265 * SEMI or ANTI join: executor will stop after first match.
2267 * For an outer-rel row that has at least one match, we can expect the
2268 * bucket scan to stop after a fraction 1/(match_count+1) of the
2269 * bucket's rows, if the matches are evenly distributed. Since they
2270 * probably aren't quite evenly distributed, we apply a fuzz factor of
2271 * 2.0 to that fraction. (If we used a larger fuzz factor, we'd have
2272 * to clamp inner_scan_frac to at most 1.0; but since match_count is
2273 * at least 1, no such clamp is needed now.)
2275 outer_matched_rows = rint(outer_path_rows * outer_match_frac);
2276 inner_scan_frac = 2.0 / (match_count + 1.0);
2278 startup_cost += hash_qual_cost.startup;
2279 run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
2280 clamp_row_est(inner_path_rows * innerbucketsize * inner_scan_frac) * 0.5;
2283 * For unmatched outer-rel rows, the picture is quite a lot different.
2284 * In the first place, there is no reason to assume that these rows
2285 * preferentially hit heavily-populated buckets; instead assume they
2286 * are uncorrelated with the inner distribution and so they see an
2287 * average bucket size of inner_path_rows / virtualbuckets. In the
2288 * second place, it seems likely that they will have few if any exact
2289 * hash-code matches and so very few of the tuples in the bucket will
2290 * actually require eval of the hash quals. We don't have any good
2291 * way to estimate how many will, but for the moment assume that the
2292 * effective cost per bucket entry is one-tenth what it is for
2295 run_cost += hash_qual_cost.per_tuple *
2296 (outer_path_rows - outer_matched_rows) *
2297 clamp_row_est(inner_path_rows / virtualbuckets) * 0.05;
2299 /* Get # of tuples that will pass the basic join */
2300 if (path->jpath.jointype == JOIN_SEMI)
2301 hashjointuples = outer_matched_rows;
2303 hashjointuples = outer_path_rows - outer_matched_rows;
2308 * The number of tuple comparisons needed is the number of outer
2309 * tuples times the typical number of tuples in a hash bucket, which
2310 * is the inner relation size times its bucketsize fraction. At each
2311 * one, we need to evaluate the hashjoin quals. But actually,
2312 * charging the full qual eval cost at each tuple is pessimistic,
2313 * since we don't evaluate the quals unless the hash values match
2314 * exactly. For lack of a better idea, halve the cost estimate to
2317 startup_cost += hash_qual_cost.startup;
2318 run_cost += hash_qual_cost.per_tuple * outer_path_rows *
2319 clamp_row_est(inner_path_rows * innerbucketsize) * 0.5;
2322 * Get approx # tuples passing the hashquals. We use
2323 * approx_tuple_count here because we need an estimate done with
2324 * JOIN_INNER semantics.
2326 hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
2330 * For each tuple that gets through the hashjoin proper, we charge
2331 * cpu_tuple_cost plus the cost of evaluating additional restriction
2332 * clauses that are to be applied at the join. (This is pessimistic since
2333 * not all of the quals may get evaluated at each tuple.)
2335 startup_cost += qp_qual_cost.startup;
2336 cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
2337 run_cost += cpu_per_tuple * hashjointuples;
2339 path->jpath.path.startup_cost = startup_cost;
2340 path->jpath.path.total_cost = startup_cost + run_cost;
2346 * Figure the costs for a SubPlan (or initplan).
2348 * Note: we could dig the subplan's Plan out of the root list, but in practice
2349 * all callers have it handy already, so we make them pass it.
2352 cost_subplan(PlannerInfo *root, SubPlan *subplan, Plan *plan)
2356 /* Figure any cost for evaluating the testexpr */
2357 cost_qual_eval(&sp_cost,
2358 make_ands_implicit((Expr *) subplan->testexpr),
2361 if (subplan->useHashTable)
2364 * If we are using a hash table for the subquery outputs, then the
2365 * cost of evaluating the query is a one-time cost. We charge one
2366 * cpu_operator_cost per tuple for the work of loading the hashtable,
2369 sp_cost.startup += plan->total_cost +
2370 cpu_operator_cost * plan->plan_rows;
2373 * The per-tuple costs include the cost of evaluating the lefthand
2374 * expressions, plus the cost of probing the hashtable. We already
2375 * accounted for the lefthand expressions as part of the testexpr, and
2376 * will also have counted one cpu_operator_cost for each comparison
2377 * operator. That is probably too low for the probing cost, but it's
2378 * hard to make a better estimate, so live with it for now.
2384 * Otherwise we will be rescanning the subplan output on each
2385 * evaluation. We need to estimate how much of the output we will
2386 * actually need to scan. NOTE: this logic should agree with the
2387 * tuple_fraction estimates used by make_subplan() in
2390 Cost plan_run_cost = plan->total_cost - plan->startup_cost;
2392 if (subplan->subLinkType == EXISTS_SUBLINK)
2394 /* we only need to fetch 1 tuple */
2395 sp_cost.per_tuple += plan_run_cost / plan->plan_rows;
2397 else if (subplan->subLinkType == ALL_SUBLINK ||
2398 subplan->subLinkType == ANY_SUBLINK)
2400 /* assume we need 50% of the tuples */
2401 sp_cost.per_tuple += 0.50 * plan_run_cost;
2402 /* also charge a cpu_operator_cost per row examined */
2403 sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
2407 /* assume we need all tuples */
2408 sp_cost.per_tuple += plan_run_cost;
2412 * Also account for subplan's startup cost. If the subplan is
2413 * uncorrelated or undirect correlated, AND its topmost node is one
2414 * that materializes its output, assume that we'll only need to pay
2415 * its startup cost once; otherwise assume we pay the startup cost
2418 if (subplan->parParam == NIL &&
2419 ExecMaterializesOutput(nodeTag(plan)))
2420 sp_cost.startup += plan->startup_cost;
2422 sp_cost.per_tuple += plan->startup_cost;
2425 subplan->startup_cost = sp_cost.startup;
2426 subplan->per_call_cost = sp_cost.per_tuple;
2432 * Given a finished Path, estimate the costs of rescanning it after
2433 * having done so the first time. For some Path types a rescan is
2434 * cheaper than an original scan (if no parameters change), and this
2435 * function embodies knowledge about that. The default is to return
2436 * the same costs stored in the Path. (Note that the cost estimates
2437 * actually stored in Paths are always for first scans.)
2439 * This function is not currently intended to model effects such as rescans
2440 * being cheaper due to disk block caching; what we are concerned with is
2441 * plan types wherein the executor caches results explicitly, or doesn't
2442 * redo startup calculations, etc.
2445 cost_rescan(PlannerInfo *root, Path *path,
2446 Cost *rescan_startup_cost, /* output parameters */
2447 Cost *rescan_total_cost)
2449 switch (path->pathtype)
2451 case T_FunctionScan:
2454 * Currently, nodeFunctionscan.c always executes the function to
2455 * completion before returning any rows, and caches the results in
2456 * a tuplestore. So the function eval cost is all startup cost
2457 * and isn't paid over again on rescans. However, all run costs
2458 * will be paid over again.
2460 *rescan_startup_cost = 0;
2461 *rescan_total_cost = path->total_cost - path->startup_cost;
2466 * Assume that all of the startup cost represents hash table
2467 * building, which we won't have to do over.
2469 *rescan_startup_cost = 0;
2470 *rescan_total_cost = path->total_cost - path->startup_cost;
2473 case T_WorkTableScan:
2476 * These plan types materialize their final result in a
2477 * tuplestore or tuplesort object. So the rescan cost is only
2478 * cpu_tuple_cost per tuple, unless the result is large enough
2481 Cost run_cost = cpu_tuple_cost * path->parent->rows;
2482 double nbytes = relation_byte_size(path->parent->rows,
2483 path->parent->width);
2484 long work_mem_bytes = work_mem * 1024L;
2486 if (nbytes > work_mem_bytes)
2488 /* It will spill, so account for re-read cost */
2489 double npages = ceil(nbytes / BLCKSZ);
2491 run_cost += seq_page_cost * npages;
2493 *rescan_startup_cost = 0;
2494 *rescan_total_cost = run_cost;
2501 * These plan types not only materialize their results, but do
2502 * not implement qual filtering or projection. So they are
2503 * even cheaper to rescan than the ones above. We charge only
2504 * cpu_operator_cost per tuple. (Note: keep that in sync with
2505 * the run_cost charge in cost_sort, and also see comments in
2506 * cost_material before you change it.)
2508 Cost run_cost = cpu_operator_cost * path->parent->rows;
2509 double nbytes = relation_byte_size(path->parent->rows,
2510 path->parent->width);
2511 long work_mem_bytes = work_mem * 1024L;
2513 if (nbytes > work_mem_bytes)
2515 /* It will spill, so account for re-read cost */
2516 double npages = ceil(nbytes / BLCKSZ);
2518 run_cost += seq_page_cost * npages;
2520 *rescan_startup_cost = 0;
2521 *rescan_total_cost = run_cost;
2525 *rescan_startup_cost = path->startup_cost;
2526 *rescan_total_cost = path->total_cost;
2534 * Estimate the CPU costs of evaluating a WHERE clause.
2535 * The input can be either an implicitly-ANDed list of boolean
2536 * expressions, or a list of RestrictInfo nodes. (The latter is
2537 * preferred since it allows caching of the results.)
2538 * The result includes both a one-time (startup) component,
2539 * and a per-evaluation component.
2542 cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
2544 cost_qual_eval_context context;
2547 context.root = root;
2548 context.total.startup = 0;
2549 context.total.per_tuple = 0;
2551 /* We don't charge any cost for the implicit ANDing at top level ... */
2555 Node *qual = (Node *) lfirst(l);
2557 cost_qual_eval_walker(qual, &context);
2560 *cost = context.total;
2564 * cost_qual_eval_node
2565 * As above, for a single RestrictInfo or expression.
2568 cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
2570 cost_qual_eval_context context;
2572 context.root = root;
2573 context.total.startup = 0;
2574 context.total.per_tuple = 0;
2576 cost_qual_eval_walker(qual, &context);
2578 *cost = context.total;
2582 cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
2588 * RestrictInfo nodes contain an eval_cost field reserved for this
2589 * routine's use, so that it's not necessary to evaluate the qual clause's
2590 * cost more than once. If the clause's cost hasn't been computed yet,
2591 * the field's startup value will contain -1.
2593 if (IsA(node, RestrictInfo))
2595 RestrictInfo *rinfo = (RestrictInfo *) node;
2597 if (rinfo->eval_cost.startup < 0)
2599 cost_qual_eval_context locContext;
2601 locContext.root = context->root;
2602 locContext.total.startup = 0;
2603 locContext.total.per_tuple = 0;
2606 * For an OR clause, recurse into the marked-up tree so that we
2607 * set the eval_cost for contained RestrictInfos too.
2609 if (rinfo->orclause)
2610 cost_qual_eval_walker((Node *) rinfo->orclause, &locContext);
2612 cost_qual_eval_walker((Node *) rinfo->clause, &locContext);
2615 * If the RestrictInfo is marked pseudoconstant, it will be tested
2616 * only once, so treat its cost as all startup cost.
2618 if (rinfo->pseudoconstant)
2620 /* count one execution during startup */
2621 locContext.total.startup += locContext.total.per_tuple;
2622 locContext.total.per_tuple = 0;
2624 rinfo->eval_cost = locContext.total;
2626 context->total.startup += rinfo->eval_cost.startup;
2627 context->total.per_tuple += rinfo->eval_cost.per_tuple;
2628 /* do NOT recurse into children */
2633 * For each operator or function node in the given tree, we charge the
2634 * estimated execution cost given by pg_proc.procost (remember to multiply
2635 * this by cpu_operator_cost).
2637 * Vars and Consts are charged zero, and so are boolean operators (AND,
2638 * OR, NOT). Simplistic, but a lot better than no model at all.
2640 * Note that Aggref and WindowFunc nodes are (and should be) treated like
2641 * Vars --- whatever execution cost they have is absorbed into
2642 * plan-node-specific costing. As far as expression evaluation is
2643 * concerned they're just like Vars.
2645 * Should we try to account for the possibility of short-circuit
2646 * evaluation of AND/OR? Probably *not*, because that would make the
2647 * results depend on the clause ordering, and we are not in any position
2648 * to expect that the current ordering of the clauses is the one that's
2649 * going to end up being used. (Is it worth applying order_qual_clauses
2650 * much earlier in the planning process to fix this?)
2652 if (IsA(node, FuncExpr))
2654 context->total.per_tuple +=
2655 get_func_cost(((FuncExpr *) node)->funcid) * cpu_operator_cost;
2657 else if (IsA(node, OpExpr) ||
2658 IsA(node, DistinctExpr) ||
2659 IsA(node, NullIfExpr))
2661 /* rely on struct equivalence to treat these all alike */
2662 set_opfuncid((OpExpr *) node);
2663 context->total.per_tuple +=
2664 get_func_cost(((OpExpr *) node)->opfuncid) * cpu_operator_cost;
2666 else if (IsA(node, ScalarArrayOpExpr))
2669 * Estimate that the operator will be applied to about half of the
2670 * array elements before the answer is determined.
2672 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
2673 Node *arraynode = (Node *) lsecond(saop->args);
2675 set_sa_opfuncid(saop);
2676 context->total.per_tuple += get_func_cost(saop->opfuncid) *
2677 cpu_operator_cost * estimate_array_length(arraynode) * 0.5;
2679 else if (IsA(node, CoerceViaIO))
2681 CoerceViaIO *iocoerce = (CoerceViaIO *) node;
2686 /* check the result type's input function */
2687 getTypeInputInfo(iocoerce->resulttype,
2688 &iofunc, &typioparam);
2689 context->total.per_tuple += get_func_cost(iofunc) * cpu_operator_cost;
2690 /* check the input type's output function */
2691 getTypeOutputInfo(exprType((Node *) iocoerce->arg),
2692 &iofunc, &typisvarlena);
2693 context->total.per_tuple += get_func_cost(iofunc) * cpu_operator_cost;
2695 else if (IsA(node, ArrayCoerceExpr))
2697 ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
2698 Node *arraynode = (Node *) acoerce->arg;
2700 if (OidIsValid(acoerce->elemfuncid))
2701 context->total.per_tuple += get_func_cost(acoerce->elemfuncid) *
2702 cpu_operator_cost * estimate_array_length(arraynode);
2704 else if (IsA(node, RowCompareExpr))
2706 /* Conservatively assume we will check all the columns */
2707 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
2710 foreach(lc, rcexpr->opnos)
2712 Oid opid = lfirst_oid(lc);
2714 context->total.per_tuple += get_func_cost(get_opcode(opid)) *
2718 else if (IsA(node, CurrentOfExpr))
2720 /* Report high cost to prevent selection of anything but TID scan */
2721 context->total.startup += disable_cost;
2723 else if (IsA(node, SubLink))
2725 /* This routine should not be applied to un-planned expressions */
2726 elog(ERROR, "cannot handle unplanned sub-select");
2728 else if (IsA(node, SubPlan))
2731 * A subplan node in an expression typically indicates that the
2732 * subplan will be executed on each evaluation, so charge accordingly.
2733 * (Sub-selects that can be executed as InitPlans have already been
2734 * removed from the expression.)
2736 SubPlan *subplan = (SubPlan *) node;
2738 context->total.startup += subplan->startup_cost;
2739 context->total.per_tuple += subplan->per_call_cost;
2742 * We don't want to recurse into the testexpr, because it was already
2743 * counted in the SubPlan node's costs. So we're done.
2747 else if (IsA(node, AlternativeSubPlan))
2750 * Arbitrarily use the first alternative plan for costing. (We should
2751 * certainly only include one alternative, and we don't yet have
2752 * enough information to know which one the executor is most likely to
2755 AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
2757 return cost_qual_eval_walker((Node *) linitial(asplan->subplans),
2761 /* recurse into children */
2762 return expression_tree_walker(node, cost_qual_eval_walker,
2769 * Estimate how much of the inner input a SEMI or ANTI join
2770 * can be expected to scan.
2772 * In a hash or nestloop SEMI/ANTI join, the executor will stop scanning
2773 * inner rows as soon as it finds a match to the current outer row.
2774 * We should therefore adjust some of the cost components for this effect.
2775 * This function computes some estimates needed for these adjustments.
2777 * 'path' is already filled in except for the cost fields
2778 * 'sjinfo' is extra info about the join for selectivity estimation
2780 * Returns TRUE if this is a SEMI or ANTI join, FALSE if not.
2782 * Output parameters (set only in TRUE-result case):
2783 * *outer_match_frac is set to the fraction of the outer tuples that are
2784 * expected to have at least one match.
2785 * *match_count is set to the average number of matches expected for
2786 * outer tuples that have at least one match.
2787 * *indexed_join_quals is set to TRUE if all the joinquals are used as
2788 * inner index quals, FALSE if not.
2790 * indexed_join_quals can be passed as NULL if that information is not
2791 * relevant (it is only useful for the nestloop case).
2794 adjust_semi_join(PlannerInfo *root, JoinPath *path, SpecialJoinInfo *sjinfo,
2795 Selectivity *outer_match_frac,
2796 Selectivity *match_count,
2797 bool *indexed_join_quals)
2799 JoinType jointype = path->jointype;
2802 Selectivity avgmatch;
2803 SpecialJoinInfo norm_sjinfo;
2807 /* Fall out if it's not JOIN_SEMI or JOIN_ANTI */
2808 if (jointype != JOIN_SEMI && jointype != JOIN_ANTI)
2812 * Note: it's annoying to repeat this selectivity estimation on each call,
2813 * when the joinclause list will be the same for all path pairs
2814 * implementing a given join. clausesel.c will save us from the worst
2815 * effects of this by caching at the RestrictInfo level; but perhaps it'd
2816 * be worth finding a way to cache the results at a higher level.
2820 * In an ANTI join, we must ignore clauses that are "pushed down", since
2821 * those won't affect the match logic. In a SEMI join, we do not
2822 * distinguish joinquals from "pushed down" quals, so just use the whole
2823 * restrictinfo list.
2825 if (jointype == JOIN_ANTI)
2828 foreach(l, path->joinrestrictinfo)
2830 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
2832 Assert(IsA(rinfo, RestrictInfo));
2833 if (!rinfo->is_pushed_down)
2834 joinquals = lappend(joinquals, rinfo);
2838 joinquals = path->joinrestrictinfo;
2841 * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
2843 jselec = clauselist_selectivity(root,
2850 * Also get the normal inner-join selectivity of the join clauses.
2852 norm_sjinfo.type = T_SpecialJoinInfo;
2853 norm_sjinfo.min_lefthand = path->outerjoinpath->parent->relids;
2854 norm_sjinfo.min_righthand = path->innerjoinpath->parent->relids;
2855 norm_sjinfo.syn_lefthand = path->outerjoinpath->parent->relids;
2856 norm_sjinfo.syn_righthand = path->innerjoinpath->parent->relids;
2857 norm_sjinfo.jointype = JOIN_INNER;
2858 /* we don't bother trying to make the remaining fields valid */
2859 norm_sjinfo.lhs_strict = false;
2860 norm_sjinfo.delay_upper_joins = false;
2861 norm_sjinfo.join_quals = NIL;
2863 nselec = clauselist_selectivity(root,
2869 /* Avoid leaking a lot of ListCells */
2870 if (jointype == JOIN_ANTI)
2871 list_free(joinquals);
2874 * jselec can be interpreted as the fraction of outer-rel rows that have
2875 * any matches (this is true for both SEMI and ANTI cases). And nselec is
2876 * the fraction of the Cartesian product that matches. So, the average
2877 * number of matches for each outer-rel row that has at least one match is
2878 * nselec * inner_rows / jselec.
2880 * Note: it is correct to use the inner rel's "rows" count here, not
2881 * PATH_ROWS(), even if the inner path under consideration is an inner
2882 * indexscan. This is because we have included all the join clauses in
2883 * the selectivity estimate, even ones used in an inner indexscan.
2885 if (jselec > 0) /* protect against zero divide */
2887 avgmatch = nselec * path->innerjoinpath->parent->rows / jselec;
2888 /* Clamp to sane range */
2889 avgmatch = Max(1.0, avgmatch);
2894 *outer_match_frac = jselec;
2895 *match_count = avgmatch;
2898 * If requested, check whether the inner path uses all the joinquals as
2899 * indexquals. (If that's true, we can assume that an unmatched outer
2900 * tuple is cheap to process, whereas otherwise it's probably expensive.)
2902 if (indexed_join_quals)
2904 if (path->joinrestrictinfo != NIL)
2908 nrclauses = select_nonredundant_join_clauses(root,
2909 path->joinrestrictinfo,
2910 path->innerjoinpath);
2911 *indexed_join_quals = (nrclauses == NIL);
2915 /* a clauseless join does NOT qualify */
2916 *indexed_join_quals = false;
2925 * approx_tuple_count
2926 * Quick-and-dirty estimation of the number of join rows passing
2927 * a set of qual conditions.
2929 * The quals can be either an implicitly-ANDed list of boolean expressions,
2930 * or a list of RestrictInfo nodes (typically the latter).
2932 * We intentionally compute the selectivity under JOIN_INNER rules, even
2933 * if it's some type of outer join. This is appropriate because we are
2934 * trying to figure out how many tuples pass the initial merge or hash
2937 * This is quick-and-dirty because we bypass clauselist_selectivity, and
2938 * simply multiply the independent clause selectivities together. Now
2939 * clauselist_selectivity often can't do any better than that anyhow, but
2940 * for some situations (such as range constraints) it is smarter. However,
2941 * we can't effectively cache the results of clauselist_selectivity, whereas
2942 * the individual clause selectivities can be and are cached.
2944 * Since we are only using the results to estimate how many potential
2945 * output tuples are generated and passed through qpqual checking, it
2946 * seems OK to live with the approximation.
2949 approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
2952 double outer_tuples = path->outerjoinpath->parent->rows;
2953 double inner_tuples = path->innerjoinpath->parent->rows;
2954 SpecialJoinInfo sjinfo;
2955 Selectivity selec = 1.0;
2959 * Make up a SpecialJoinInfo for JOIN_INNER semantics.
2961 sjinfo.type = T_SpecialJoinInfo;
2962 sjinfo.min_lefthand = path->outerjoinpath->parent->relids;
2963 sjinfo.min_righthand = path->innerjoinpath->parent->relids;
2964 sjinfo.syn_lefthand = path->outerjoinpath->parent->relids;
2965 sjinfo.syn_righthand = path->innerjoinpath->parent->relids;
2966 sjinfo.jointype = JOIN_INNER;
2967 /* we don't bother trying to make the remaining fields valid */
2968 sjinfo.lhs_strict = false;
2969 sjinfo.delay_upper_joins = false;
2970 sjinfo.join_quals = NIL;
2972 /* Get the approximate selectivity */
2975 Node *qual = (Node *) lfirst(l);
2977 /* Note that clause_selectivity will be able to cache its result */
2978 selec *= clause_selectivity(root, qual, 0, JOIN_INNER, &sjinfo);
2981 /* Apply it to the input relation sizes */
2982 tuples = selec * outer_tuples * inner_tuples;
2984 return clamp_row_est(tuples);
2989 * set_baserel_size_estimates
2990 * Set the size estimates for the given base relation.
2992 * The rel's targetlist and restrictinfo list must have been constructed
2993 * already, and rel->tuples must be set.
2995 * We set the following fields of the rel node:
2996 * rows: the estimated number of output tuples (after applying
2997 * restriction clauses).
2998 * width: the estimated average output tuple width in bytes.
2999 * baserestrictcost: estimated cost of evaluating baserestrictinfo clauses.
3002 set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3006 /* Should only be applied to base relations */
3007 Assert(rel->relid > 0);
3009 nrows = rel->tuples *
3010 clauselist_selectivity(root,
3011 rel->baserestrictinfo,
3016 rel->rows = clamp_row_est(nrows);
3018 cost_qual_eval(&rel->baserestrictcost, rel->baserestrictinfo, root);
3020 set_rel_width(root, rel);
3024 * set_joinrel_size_estimates
3025 * Set the size estimates for the given join relation.
3027 * The rel's targetlist must have been constructed already, and a
3028 * restriction clause list that matches the given component rels must
3031 * Since there is more than one way to make a joinrel for more than two
3032 * base relations, the results we get here could depend on which component
3033 * rel pair is provided. In theory we should get the same answers no matter
3034 * which pair is provided; in practice, since the selectivity estimation
3035 * routines don't handle all cases equally well, we might not. But there's
3036 * not much to be done about it. (Would it make sense to repeat the
3037 * calculations for each pair of input rels that's encountered, and somehow
3038 * average the results? Probably way more trouble than it's worth.)
3040 * We set only the rows field here. The width field was already set by
3041 * build_joinrel_tlist, and baserestrictcost is not used for join rels.
3044 set_joinrel_size_estimates(PlannerInfo *root, RelOptInfo *rel,
3045 RelOptInfo *outer_rel,
3046 RelOptInfo *inner_rel,
3047 SpecialJoinInfo *sjinfo,
3050 JoinType jointype = sjinfo->jointype;
3056 * Compute joinclause selectivity. Note that we are only considering
3057 * clauses that become restriction clauses at this join level; we are not
3058 * double-counting them because they were not considered in estimating the
3059 * sizes of the component rels.
3061 * For an outer join, we have to distinguish the selectivity of the join's
3062 * own clauses (JOIN/ON conditions) from any clauses that were "pushed
3063 * down". For inner joins we just count them all as joinclauses.
3065 if (IS_OUTER_JOIN(jointype))
3067 List *joinquals = NIL;
3068 List *pushedquals = NIL;
3071 /* Grovel through the clauses to separate into two lists */
3072 foreach(l, restrictlist)
3074 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
3076 Assert(IsA(rinfo, RestrictInfo));
3077 if (rinfo->is_pushed_down)
3078 pushedquals = lappend(pushedquals, rinfo);
3080 joinquals = lappend(joinquals, rinfo);
3083 /* Get the separate selectivities */
3084 jselec = clauselist_selectivity(root,
3089 pselec = clauselist_selectivity(root,
3095 /* Avoid leaking a lot of ListCells */
3096 list_free(joinquals);
3097 list_free(pushedquals);
3101 jselec = clauselist_selectivity(root,
3106 pselec = 0.0; /* not used, keep compiler quiet */
3110 * Basically, we multiply size of Cartesian product by selectivity.
3112 * If we are doing an outer join, take that into account: the joinqual
3113 * selectivity has to be clamped using the knowledge that the output must
3114 * be at least as large as the non-nullable input. However, any
3115 * pushed-down quals are applied after the outer join, so their
3116 * selectivity applies fully.
3118 * For JOIN_SEMI and JOIN_ANTI, the selectivity is defined as the fraction
3119 * of LHS rows that have matches, and we apply that straightforwardly.
3124 nrows = outer_rel->rows * inner_rel->rows * jselec;
3127 nrows = outer_rel->rows * inner_rel->rows * jselec;
3128 if (nrows < outer_rel->rows)
3129 nrows = outer_rel->rows;
3133 nrows = outer_rel->rows * inner_rel->rows * jselec;
3134 if (nrows < outer_rel->rows)
3135 nrows = outer_rel->rows;
3136 if (nrows < inner_rel->rows)
3137 nrows = inner_rel->rows;
3141 nrows = outer_rel->rows * jselec;
3142 /* pselec not used */
3145 nrows = outer_rel->rows * (1.0 - jselec);
3149 /* other values not expected here */
3150 elog(ERROR, "unrecognized join type: %d", (int) jointype);
3151 nrows = 0; /* keep compiler quiet */
3155 rel->rows = clamp_row_est(nrows);
3159 * set_subquery_size_estimates
3160 * Set the size estimates for a base relation that is a subquery.
3162 * The rel's targetlist and restrictinfo list must have been constructed
3163 * already, and the plan for the subquery must have been completed.
3164 * We look at the subquery's plan and PlannerInfo to extract data.
3166 * We set the same fields as set_baserel_size_estimates.
3169 set_subquery_size_estimates(PlannerInfo *root, RelOptInfo *rel,
3170 PlannerInfo *subroot)
3175 /* Should only be applied to base relations that are subqueries */
3176 Assert(rel->relid > 0);
3177 rte = planner_rt_fetch(rel->relid, root);
3178 Assert(rte->rtekind == RTE_SUBQUERY);
3180 /* Copy raw number of output rows from subplan */
3181 rel->tuples = rel->subplan->plan_rows;
3184 * Compute per-output-column width estimates by examining the subquery's
3185 * targetlist. For any output that is a plain Var, get the width estimate
3186 * that was made while planning the subquery. Otherwise, fall back on a
3187 * datatype-based estimate.
3189 foreach(lc, subroot->parse->targetList)
3191 TargetEntry *te = (TargetEntry *) lfirst(lc);
3192 Node *texpr = (Node *) te->expr;
3195 Assert(IsA(te, TargetEntry));
3196 /* junk columns aren't visible to upper query */
3201 * XXX This currently doesn't work for subqueries containing set
3202 * operations, because the Vars in their tlists are bogus references
3203 * to the first leaf subquery, which wouldn't give the right answer
3204 * even if we could still get to its PlannerInfo. So fall back on
3205 * datatype in that case.
3207 if (IsA(texpr, Var) &&
3208 subroot->parse->setOperations == NULL)
3210 Var *var = (Var *) texpr;
3211 RelOptInfo *subrel = find_base_rel(subroot, var->varno);
3213 item_width = subrel->attr_widths[var->varattno - subrel->min_attr];
3217 item_width = get_typavgwidth(exprType(texpr), exprTypmod(texpr));
3219 Assert(item_width > 0);
3220 Assert(te->resno >= rel->min_attr && te->resno <= rel->max_attr);
3221 rel->attr_widths[te->resno - rel->min_attr] = item_width;
3224 /* Now estimate number of output rows, etc */
3225 set_baserel_size_estimates(root, rel);
3229 * set_function_size_estimates
3230 * Set the size estimates for a base relation that is a function call.
3232 * The rel's targetlist and restrictinfo list must have been constructed
3235 * We set the same fields as set_baserel_size_estimates.
3238 set_function_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3242 /* Should only be applied to base relations that are functions */
3243 Assert(rel->relid > 0);
3244 rte = planner_rt_fetch(rel->relid, root);
3245 Assert(rte->rtekind == RTE_FUNCTION);
3247 /* Estimate number of rows the function itself will return */
3248 rel->tuples = clamp_row_est(expression_returns_set_rows(rte->funcexpr));
3250 /* Now estimate number of output rows, etc */
3251 set_baserel_size_estimates(root, rel);
3255 * set_values_size_estimates
3256 * Set the size estimates for a base relation that is a values list.
3258 * The rel's targetlist and restrictinfo list must have been constructed
3261 * We set the same fields as set_baserel_size_estimates.
3264 set_values_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3268 /* Should only be applied to base relations that are values lists */
3269 Assert(rel->relid > 0);
3270 rte = planner_rt_fetch(rel->relid, root);
3271 Assert(rte->rtekind == RTE_VALUES);
3274 * Estimate number of rows the values list will return. We know this
3275 * precisely based on the list length (well, barring set-returning
3276 * functions in list items, but that's a refinement not catered for
3277 * anywhere else either).
3279 rel->tuples = list_length(rte->values_lists);
3281 /* Now estimate number of output rows, etc */
3282 set_baserel_size_estimates(root, rel);
3286 * set_cte_size_estimates
3287 * Set the size estimates for a base relation that is a CTE reference.
3289 * The rel's targetlist and restrictinfo list must have been constructed
3290 * already, and we need the completed plan for the CTE (if a regular CTE)
3291 * or the non-recursive term (if a self-reference).
3293 * We set the same fields as set_baserel_size_estimates.
3296 set_cte_size_estimates(PlannerInfo *root, RelOptInfo *rel, Plan *cteplan)
3300 /* Should only be applied to base relations that are CTE references */
3301 Assert(rel->relid > 0);
3302 rte = planner_rt_fetch(rel->relid, root);
3303 Assert(rte->rtekind == RTE_CTE);
3305 if (rte->self_reference)
3308 * In a self-reference, arbitrarily assume the average worktable size
3309 * is about 10 times the nonrecursive term's size.
3311 rel->tuples = 10 * cteplan->plan_rows;
3315 /* Otherwise just believe the CTE plan's output estimate */
3316 rel->tuples = cteplan->plan_rows;
3319 /* Now estimate number of output rows, etc */
3320 set_baserel_size_estimates(root, rel);
3326 * Set the estimated output width of a base relation.
3328 * The estimated output width is the sum of the per-attribute width estimates
3329 * for the actually-referenced columns, plus any PHVs or other expressions
3330 * that have to be calculated at this relation. This is the amount of data
3331 * we'd need to pass upwards in case of a sort, hash, etc.
3333 * NB: this works best on plain relations because it prefers to look at
3334 * real Vars. For subqueries, set_subquery_size_estimates will already have
3335 * copied up whatever per-column estimates were made within the subquery,
3336 * and for other types of rels there isn't much we can do anyway. We fall
3337 * back on (fairly stupid) datatype-based width estimates if we can't get
3338 * any better number.
3340 * The per-attribute width estimates are cached for possible re-use while
3341 * building join relations.
3344 set_rel_width(PlannerInfo *root, RelOptInfo *rel)
3346 Oid reloid = planner_rt_fetch(rel->relid, root)->relid;
3347 int32 tuple_width = 0;
3348 bool have_wholerow_var = false;
3351 foreach(lc, rel->reltargetlist)
3353 Node *node = (Node *) lfirst(lc);
3357 Var *var = (Var *) node;
3361 Assert(var->varno == rel->relid);
3362 Assert(var->varattno >= rel->min_attr);
3363 Assert(var->varattno <= rel->max_attr);
3365 ndx = var->varattno - rel->min_attr;
3368 * If it's a whole-row Var, we'll deal with it below after we
3369 * have already cached as many attr widths as possible.
3371 if (var->varattno == 0)
3373 have_wholerow_var = true;
3378 * The width may have been cached already (especially if it's
3379 * a subquery), so don't duplicate effort.
3381 if (rel->attr_widths[ndx] > 0)
3383 tuple_width += rel->attr_widths[ndx];
3387 /* Try to get column width from statistics */
3388 if (reloid != InvalidOid && var->varattno > 0)
3390 item_width = get_attavgwidth(reloid, var->varattno);
3393 rel->attr_widths[ndx] = item_width;
3394 tuple_width += item_width;
3400 * Not a plain relation, or can't find statistics for it. Estimate
3401 * using just the type info.
3403 item_width = get_typavgwidth(var->vartype, var->vartypmod);
3404 Assert(item_width > 0);
3405 rel->attr_widths[ndx] = item_width;
3406 tuple_width += item_width;
3408 else if (IsA(node, PlaceHolderVar))
3410 PlaceHolderVar *phv = (PlaceHolderVar *) node;
3411 PlaceHolderInfo *phinfo = find_placeholder_info(root, phv);
3413 tuple_width += phinfo->ph_width;
3418 * We could be looking at an expression pulled up from a subquery,
3419 * or a ROW() representing a whole-row child Var, etc. Do what we
3420 * can using the expression type information.
3424 item_width = get_typavgwidth(exprType(node), exprTypmod(node));
3425 Assert(item_width > 0);
3426 tuple_width += item_width;
3431 * If we have a whole-row reference, estimate its width as the sum of
3432 * per-column widths plus sizeof(HeapTupleHeaderData).
3434 if (have_wholerow_var)
3436 int32 wholerow_width = sizeof(HeapTupleHeaderData);
3438 if (reloid != InvalidOid)
3440 /* Real relation, so estimate true tuple width */
3441 wholerow_width += get_relation_data_width(reloid,
3442 rel->attr_widths - rel->min_attr);
3446 /* Do what we can with info for a phony rel */
3449 for (i = 1; i <= rel->max_attr; i++)
3450 wholerow_width += rel->attr_widths[i - rel->min_attr];
3453 rel->attr_widths[0 - rel->min_attr] = wholerow_width;
3456 * Include the whole-row Var as part of the output tuple. Yes,
3457 * that really is what happens at runtime.
3459 tuple_width += wholerow_width;
3462 Assert(tuple_width >= 0);
3463 rel->width = tuple_width;
3467 * relation_byte_size
3468 * Estimate the storage space in bytes for a given number of tuples
3469 * of a given width (size in bytes).
3472 relation_byte_size(double tuples, int width)
3474 return tuples * (MAXALIGN(width) + MAXALIGN(sizeof(HeapTupleHeaderData)));
3479 * Returns an estimate of the number of pages covered by a given
3480 * number of tuples of a given width (size in bytes).
3483 page_size(double tuples, int width)
3485 return ceil(relation_byte_size(tuples, width) / BLCKSZ);