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 * $PostgreSQL: pgsql/src/backend/optimizer/path/costsize.c,v 1.217 2010/04/19 00:55:25 rhaas Exp $
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/planmain.h"
80 #include "optimizer/restrictinfo.h"
81 #include "parser/parsetree.h"
82 #include "utils/lsyscache.h"
83 #include "utils/selfuncs.h"
84 #include "utils/spccache.h"
85 #include "utils/tuplesort.h"
88 #define LOG2(x) (log(x) / 0.693147180559945)
91 * Some Paths return less than the nominal number of rows of their parent
92 * relations; join nodes need to do this to get the correct input count:
94 #define PATH_ROWS(path) \
95 (IsA(path, UniquePath) ? \
96 ((UniquePath *) (path))->rows : \
100 double seq_page_cost = DEFAULT_SEQ_PAGE_COST;
101 double random_page_cost = DEFAULT_RANDOM_PAGE_COST;
102 double cpu_tuple_cost = DEFAULT_CPU_TUPLE_COST;
103 double cpu_index_tuple_cost = DEFAULT_CPU_INDEX_TUPLE_COST;
104 double cpu_operator_cost = DEFAULT_CPU_OPERATOR_COST;
106 int effective_cache_size = DEFAULT_EFFECTIVE_CACHE_SIZE;
108 Cost disable_cost = 1.0e10;
110 bool enable_seqscan = true;
111 bool enable_indexscan = true;
112 bool enable_bitmapscan = true;
113 bool enable_tidscan = true;
114 bool enable_sort = true;
115 bool enable_hashagg = true;
116 bool enable_nestloop = true;
117 bool enable_material = true;
118 bool enable_mergejoin = true;
119 bool enable_hashjoin = true;
125 } cost_qual_eval_context;
127 static MergeScanSelCache *cached_scansel(PlannerInfo *root,
130 static void cost_rescan(PlannerInfo *root, Path *path,
131 Cost *rescan_startup_cost, Cost *rescan_total_cost);
132 static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context);
133 static bool adjust_semi_join(PlannerInfo *root, JoinPath *path,
134 SpecialJoinInfo *sjinfo,
135 Selectivity *outer_match_frac,
136 Selectivity *match_count,
137 bool *indexed_join_quals);
138 static double approx_tuple_count(PlannerInfo *root, JoinPath *path,
140 static void set_rel_width(PlannerInfo *root, RelOptInfo *rel);
141 static double relation_byte_size(double tuples, int width);
142 static double page_size(double tuples, int width);
147 * Force a row-count estimate to a sane value.
150 clamp_row_est(double nrows)
153 * Force estimate to be at least one row, to make explain output look
154 * better and to avoid possible divide-by-zero when interpolating costs.
155 * Make it an integer, too.
168 * Determines and returns the cost of scanning a relation sequentially.
171 cost_seqscan(Path *path, PlannerInfo *root,
174 double spc_seq_page_cost;
175 Cost startup_cost = 0;
179 /* Should only be applied to base relations */
180 Assert(baserel->relid > 0);
181 Assert(baserel->rtekind == RTE_RELATION);
184 startup_cost += disable_cost;
186 /* fetch estimated page cost for tablespace containing table */
187 get_tablespace_page_costs(baserel->reltablespace,
194 run_cost += spc_seq_page_cost * baserel->pages;
197 startup_cost += baserel->baserestrictcost.startup;
198 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
199 run_cost += cpu_per_tuple * baserel->tuples;
201 path->startup_cost = startup_cost;
202 path->total_cost = startup_cost + run_cost;
207 * Determines and returns the cost of scanning a relation using an index.
209 * 'index' is the index to be used
210 * 'indexQuals' is the list of applicable qual clauses (implicit AND semantics)
211 * 'outer_rel' is the outer relation when we are considering using the index
212 * scan as the inside of a nestloop join (hence, some of the indexQuals
213 * are join clauses, and we should expect repeated scans of the index);
214 * NULL for a plain index scan
216 * cost_index() takes an IndexPath not just a Path, because it sets a few
217 * additional fields of the IndexPath besides startup_cost and total_cost.
218 * These fields are needed if the IndexPath is used in a BitmapIndexScan.
220 * NOTE: 'indexQuals' must contain only clauses usable as index restrictions.
221 * Any additional quals evaluated as qpquals may reduce the number of returned
222 * tuples, but they won't reduce the number of tuples we have to fetch from
223 * the table, so they don't reduce the scan cost.
225 * NOTE: as of 8.0, indexQuals is a list of RestrictInfo nodes, where formerly
226 * it was a list of bare clause expressions.
229 cost_index(IndexPath *path, PlannerInfo *root,
232 RelOptInfo *outer_rel)
234 RelOptInfo *baserel = index->rel;
235 Cost startup_cost = 0;
237 Cost indexStartupCost;
239 Selectivity indexSelectivity;
240 double indexCorrelation,
242 double spc_seq_page_cost,
243 spc_random_page_cost;
247 double tuples_fetched;
248 double pages_fetched;
250 /* Should only be applied to base relations */
251 Assert(IsA(baserel, RelOptInfo) &&
252 IsA(index, IndexOptInfo));
253 Assert(baserel->relid > 0);
254 Assert(baserel->rtekind == RTE_RELATION);
256 if (!enable_indexscan)
257 startup_cost += disable_cost;
260 * Call index-access-method-specific code to estimate the processing cost
261 * for scanning the index, as well as the selectivity of the index (ie,
262 * the fraction of main-table tuples we will have to retrieve) and its
263 * correlation to the main-table tuple order.
265 OidFunctionCall8(index->amcostestimate,
266 PointerGetDatum(root),
267 PointerGetDatum(index),
268 PointerGetDatum(indexQuals),
269 PointerGetDatum(outer_rel),
270 PointerGetDatum(&indexStartupCost),
271 PointerGetDatum(&indexTotalCost),
272 PointerGetDatum(&indexSelectivity),
273 PointerGetDatum(&indexCorrelation));
276 * Save amcostestimate's results for possible use in bitmap scan planning.
277 * We don't bother to save indexStartupCost or indexCorrelation, because a
278 * bitmap scan doesn't care about either.
280 path->indextotalcost = indexTotalCost;
281 path->indexselectivity = indexSelectivity;
283 /* all costs for touching index itself included here */
284 startup_cost += indexStartupCost;
285 run_cost += indexTotalCost - indexStartupCost;
287 /* estimate number of main-table tuples fetched */
288 tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
290 /* fetch estimated page costs for tablespace containing table */
291 get_tablespace_page_costs(baserel->reltablespace,
292 &spc_random_page_cost,
296 * Estimate number of main-table pages fetched, and compute I/O cost.
298 * When the index ordering is uncorrelated with the table ordering,
299 * we use an approximation proposed by Mackert and Lohman (see
300 * index_pages_fetched() for details) to compute the number of pages
301 * fetched, and then charge spc_random_page_cost per page fetched.
303 * When the index ordering is exactly correlated with the table ordering
304 * (just after a CLUSTER, for example), the number of pages fetched should
305 * be exactly selectivity * table_size. What's more, all but the first
306 * will be sequential fetches, not the random fetches that occur in the
307 * uncorrelated case. So if the number of pages is more than 1, we
309 * spc_random_page_cost + (pages_fetched - 1) * spc_seq_page_cost
310 * For partially-correlated indexes, we ought to charge somewhere between
311 * these two estimates. We currently interpolate linearly between the
312 * estimates based on the correlation squared (XXX is that appropriate?).
315 if (outer_rel != NULL && outer_rel->rows > 1)
318 * For repeated indexscans, the appropriate estimate for the
319 * uncorrelated case is to scale up the number of tuples fetched in
320 * the Mackert and Lohman formula by the number of scans, so that we
321 * estimate the number of pages fetched by all the scans; then
322 * pro-rate the costs for one scan. In this case we assume all the
323 * fetches are random accesses.
325 double num_scans = outer_rel->rows;
327 pages_fetched = index_pages_fetched(tuples_fetched * num_scans,
329 (double) index->pages,
332 max_IO_cost = (pages_fetched * spc_random_page_cost) / num_scans;
335 * In the perfectly correlated case, the number of pages touched by
336 * each scan is selectivity * table_size, and we can use the Mackert
337 * and Lohman formula at the page level to estimate how much work is
338 * saved by caching across scans. We still assume all the fetches are
339 * random, though, which is an overestimate that's hard to correct for
340 * without double-counting the cache effects. (But in most cases
341 * where such a plan is actually interesting, only one page would get
342 * fetched per scan anyway, so it shouldn't matter much.)
344 pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
346 pages_fetched = index_pages_fetched(pages_fetched * num_scans,
348 (double) index->pages,
351 min_IO_cost = (pages_fetched * spc_random_page_cost) / num_scans;
356 * Normal case: apply the Mackert and Lohman formula, and then
357 * interpolate between that and the correlation-derived result.
359 pages_fetched = index_pages_fetched(tuples_fetched,
361 (double) index->pages,
364 /* max_IO_cost is for the perfectly uncorrelated case (csquared=0) */
365 max_IO_cost = pages_fetched * spc_random_page_cost;
367 /* min_IO_cost is for the perfectly correlated case (csquared=1) */
368 pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
369 min_IO_cost = spc_random_page_cost;
370 if (pages_fetched > 1)
371 min_IO_cost += (pages_fetched - 1) * spc_seq_page_cost;
375 * Now interpolate based on estimated index order correlation to get total
376 * disk I/O cost for main table accesses.
378 csquared = indexCorrelation * indexCorrelation;
380 run_cost += max_IO_cost + csquared * (min_IO_cost - max_IO_cost);
383 * Estimate CPU costs per tuple.
385 * Normally the indexquals will be removed from the list of restriction
386 * clauses that we have to evaluate as qpquals, so we should subtract
387 * their costs from baserestrictcost. But if we are doing a join then
388 * some of the indexquals are join clauses and shouldn't be subtracted.
389 * Rather than work out exactly how much to subtract, we don't subtract
392 startup_cost += baserel->baserestrictcost.startup;
393 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
395 if (outer_rel == NULL)
397 QualCost index_qual_cost;
399 cost_qual_eval(&index_qual_cost, indexQuals, root);
400 /* any startup cost still has to be paid ... */
401 cpu_per_tuple -= index_qual_cost.per_tuple;
404 run_cost += cpu_per_tuple * tuples_fetched;
406 path->path.startup_cost = startup_cost;
407 path->path.total_cost = startup_cost + run_cost;
411 * index_pages_fetched
412 * Estimate the number of pages actually fetched after accounting for
415 * We use an approximation proposed by Mackert and Lohman, "Index Scans
416 * Using a Finite LRU Buffer: A Validated I/O Model", ACM Transactions
417 * on Database Systems, Vol. 14, No. 3, September 1989, Pages 401-424.
418 * The Mackert and Lohman approximation is that the number of pages
421 * min(2TNs/(2T+Ns), T) when T <= b
422 * 2TNs/(2T+Ns) when T > b and Ns <= 2Tb/(2T-b)
423 * b + (Ns - 2Tb/(2T-b))*(T-b)/T when T > b and Ns > 2Tb/(2T-b)
425 * T = # pages in table
426 * N = # tuples in table
427 * s = selectivity = fraction of table to be scanned
428 * b = # buffer pages available (we include kernel space here)
430 * We assume that effective_cache_size is the total number of buffer pages
431 * available for the whole query, and pro-rate that space across all the
432 * tables in the query and the index currently under consideration. (This
433 * ignores space needed for other indexes used by the query, but since we
434 * don't know which indexes will get used, we can't estimate that very well;
435 * and in any case counting all the tables may well be an overestimate, since
436 * depending on the join plan not all the tables may be scanned concurrently.)
438 * The product Ns is the number of tuples fetched; we pass in that
439 * product rather than calculating it here. "pages" is the number of pages
440 * in the object under consideration (either an index or a table).
441 * "index_pages" is the amount to add to the total table space, which was
442 * computed for us by query_planner.
444 * Caller is expected to have ensured that tuples_fetched is greater than zero
445 * and rounded to integer (see clamp_row_est). The result will likewise be
446 * greater than zero and integral.
449 index_pages_fetched(double tuples_fetched, BlockNumber pages,
450 double index_pages, PlannerInfo *root)
452 double pages_fetched;
457 /* T is # pages in table, but don't allow it to be zero */
458 T = (pages > 1) ? (double) pages : 1.0;
460 /* Compute number of pages assumed to be competing for cache space */
461 total_pages = root->total_table_pages + index_pages;
462 total_pages = Max(total_pages, 1.0);
463 Assert(T <= total_pages);
465 /* b is pro-rated share of effective_cache_size */
466 b = (double) effective_cache_size *T / total_pages;
468 /* force it positive and integral */
474 /* This part is the Mackert and Lohman formula */
478 (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
479 if (pages_fetched >= T)
482 pages_fetched = ceil(pages_fetched);
488 lim = (2.0 * T * b) / (2.0 * T - b);
489 if (tuples_fetched <= lim)
492 (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
497 b + (tuples_fetched - lim) * (T - b) / T;
499 pages_fetched = ceil(pages_fetched);
501 return pages_fetched;
505 * get_indexpath_pages
506 * Determine the total size of the indexes used in a bitmap index path.
508 * Note: if the same index is used more than once in a bitmap tree, we will
509 * count it multiple times, which perhaps is the wrong thing ... but it's
510 * not completely clear, and detecting duplicates is difficult, so ignore it
514 get_indexpath_pages(Path *bitmapqual)
519 if (IsA(bitmapqual, BitmapAndPath))
521 BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
523 foreach(l, apath->bitmapquals)
525 result += get_indexpath_pages((Path *) lfirst(l));
528 else if (IsA(bitmapqual, BitmapOrPath))
530 BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
532 foreach(l, opath->bitmapquals)
534 result += get_indexpath_pages((Path *) lfirst(l));
537 else if (IsA(bitmapqual, IndexPath))
539 IndexPath *ipath = (IndexPath *) bitmapqual;
541 result = (double) ipath->indexinfo->pages;
544 elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
550 * cost_bitmap_heap_scan
551 * Determines and returns the cost of scanning a relation using a bitmap
552 * index-then-heap plan.
554 * 'baserel' is the relation to be scanned
555 * 'bitmapqual' is a tree of IndexPaths, BitmapAndPaths, and BitmapOrPaths
556 * 'outer_rel' is the outer relation when we are considering using the bitmap
557 * scan as the inside of a nestloop join (hence, some of the indexQuals
558 * are join clauses, and we should expect repeated scans of the table);
559 * NULL for a plain bitmap scan
561 * Note: if this is a join inner path, the component IndexPaths in bitmapqual
562 * should have been costed accordingly.
565 cost_bitmap_heap_scan(Path *path, PlannerInfo *root, RelOptInfo *baserel,
566 Path *bitmapqual, RelOptInfo *outer_rel)
568 Cost startup_cost = 0;
571 Selectivity indexSelectivity;
574 double tuples_fetched;
575 double pages_fetched;
576 double spc_seq_page_cost,
577 spc_random_page_cost;
580 /* Should only be applied to base relations */
581 Assert(IsA(baserel, RelOptInfo));
582 Assert(baserel->relid > 0);
583 Assert(baserel->rtekind == RTE_RELATION);
585 if (!enable_bitmapscan)
586 startup_cost += disable_cost;
589 * Fetch total cost of obtaining the bitmap, as well as its total
592 cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
594 startup_cost += indexTotalCost;
596 /* Fetch estimated page costs for tablespace containing table. */
597 get_tablespace_page_costs(baserel->reltablespace,
598 &spc_random_page_cost,
602 * Estimate number of main-table pages fetched.
604 tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
606 T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
608 if (outer_rel != NULL && outer_rel->rows > 1)
611 * For repeated bitmap scans, scale up the number of tuples fetched in
612 * the Mackert and Lohman formula by the number of scans, so that we
613 * estimate the number of pages fetched by all the scans. Then
614 * pro-rate for one scan.
616 double num_scans = outer_rel->rows;
618 pages_fetched = index_pages_fetched(tuples_fetched * num_scans,
620 get_indexpath_pages(bitmapqual),
622 pages_fetched /= num_scans;
627 * For a single scan, the number of heap pages that need to be fetched
628 * is the same as the Mackert and Lohman formula for the case T <= b
629 * (ie, no re-reads needed).
631 pages_fetched = (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
633 if (pages_fetched >= T)
636 pages_fetched = ceil(pages_fetched);
639 * For small numbers of pages we should charge spc_random_page_cost
640 * apiece, while if nearly all the table's pages are being read, it's more
641 * appropriate to charge spc_seq_page_cost apiece. The effect is
642 * nonlinear, too. For lack of a better idea, interpolate like this to
643 * determine the cost per page.
645 if (pages_fetched >= 2.0)
646 cost_per_page = spc_random_page_cost -
647 (spc_random_page_cost - spc_seq_page_cost)
648 * sqrt(pages_fetched / T);
650 cost_per_page = spc_random_page_cost;
652 run_cost += pages_fetched * cost_per_page;
655 * Estimate CPU costs per tuple.
657 * Often the indexquals don't need to be rechecked at each tuple ... but
658 * not always, especially not if there are enough tuples involved that the
659 * bitmaps become lossy. For the moment, just assume they will be
662 startup_cost += baserel->baserestrictcost.startup;
663 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
665 run_cost += cpu_per_tuple * tuples_fetched;
667 path->startup_cost = startup_cost;
668 path->total_cost = startup_cost + run_cost;
672 * cost_bitmap_tree_node
673 * Extract cost and selectivity from a bitmap tree node (index/and/or)
676 cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
678 if (IsA(path, IndexPath))
680 *cost = ((IndexPath *) path)->indextotalcost;
681 *selec = ((IndexPath *) path)->indexselectivity;
684 * Charge a small amount per retrieved tuple to reflect the costs of
685 * manipulating the bitmap. This is mostly to make sure that a bitmap
686 * scan doesn't look to be the same cost as an indexscan to retrieve a
689 *cost += 0.1 * cpu_operator_cost * ((IndexPath *) path)->rows;
691 else if (IsA(path, BitmapAndPath))
693 *cost = path->total_cost;
694 *selec = ((BitmapAndPath *) path)->bitmapselectivity;
696 else if (IsA(path, BitmapOrPath))
698 *cost = path->total_cost;
699 *selec = ((BitmapOrPath *) path)->bitmapselectivity;
703 elog(ERROR, "unrecognized node type: %d", nodeTag(path));
704 *cost = *selec = 0; /* keep compiler quiet */
709 * cost_bitmap_and_node
710 * Estimate the cost of a BitmapAnd node
712 * Note that this considers only the costs of index scanning and bitmap
713 * creation, not the eventual heap access. In that sense the object isn't
714 * truly a Path, but it has enough path-like properties (costs in particular)
715 * to warrant treating it as one.
718 cost_bitmap_and_node(BitmapAndPath *path, PlannerInfo *root)
725 * We estimate AND selectivity on the assumption that the inputs are
726 * independent. This is probably often wrong, but we don't have the info
729 * The runtime cost of the BitmapAnd itself is estimated at 100x
730 * cpu_operator_cost for each tbm_intersect needed. Probably too small,
731 * definitely too simplistic?
735 foreach(l, path->bitmapquals)
737 Path *subpath = (Path *) lfirst(l);
739 Selectivity subselec;
741 cost_bitmap_tree_node(subpath, &subCost, &subselec);
745 totalCost += subCost;
746 if (l != list_head(path->bitmapquals))
747 totalCost += 100.0 * cpu_operator_cost;
749 path->bitmapselectivity = selec;
750 path->path.startup_cost = totalCost;
751 path->path.total_cost = totalCost;
755 * cost_bitmap_or_node
756 * Estimate the cost of a BitmapOr node
758 * See comments for cost_bitmap_and_node.
761 cost_bitmap_or_node(BitmapOrPath *path, PlannerInfo *root)
768 * We estimate OR selectivity on the assumption that the inputs are
769 * non-overlapping, since that's often the case in "x IN (list)" type
770 * situations. Of course, we clamp to 1.0 at the end.
772 * The runtime cost of the BitmapOr itself is estimated at 100x
773 * cpu_operator_cost for each tbm_union needed. Probably too small,
774 * definitely too simplistic? We are aware that the tbm_unions are
775 * optimized out when the inputs are BitmapIndexScans.
779 foreach(l, path->bitmapquals)
781 Path *subpath = (Path *) lfirst(l);
783 Selectivity subselec;
785 cost_bitmap_tree_node(subpath, &subCost, &subselec);
789 totalCost += subCost;
790 if (l != list_head(path->bitmapquals) &&
791 !IsA(subpath, IndexPath))
792 totalCost += 100.0 * cpu_operator_cost;
794 path->bitmapselectivity = Min(selec, 1.0);
795 path->path.startup_cost = totalCost;
796 path->path.total_cost = totalCost;
801 * Determines and returns the cost of scanning a relation using TIDs.
804 cost_tidscan(Path *path, PlannerInfo *root,
805 RelOptInfo *baserel, List *tidquals)
807 Cost startup_cost = 0;
809 bool isCurrentOf = false;
811 QualCost tid_qual_cost;
814 double spc_random_page_cost;
816 /* Should only be applied to base relations */
817 Assert(baserel->relid > 0);
818 Assert(baserel->rtekind == RTE_RELATION);
820 /* Count how many tuples we expect to retrieve */
824 if (IsA(lfirst(l), ScalarArrayOpExpr))
826 /* Each element of the array yields 1 tuple */
827 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) lfirst(l);
828 Node *arraynode = (Node *) lsecond(saop->args);
830 ntuples += estimate_array_length(arraynode);
832 else if (IsA(lfirst(l), CurrentOfExpr))
834 /* CURRENT OF yields 1 tuple */
840 /* It's just CTID = something, count 1 tuple */
846 * We must force TID scan for WHERE CURRENT OF, because only nodeTidscan.c
847 * understands how to do it correctly. Therefore, honor enable_tidscan
848 * only when CURRENT OF isn't present. Also note that cost_qual_eval
849 * counts a CurrentOfExpr as having startup cost disable_cost, which we
850 * subtract off here; that's to prevent other plan types such as seqscan
855 Assert(baserel->baserestrictcost.startup >= disable_cost);
856 startup_cost -= disable_cost;
858 else if (!enable_tidscan)
859 startup_cost += disable_cost;
862 * The TID qual expressions will be computed once, any other baserestrict
863 * quals once per retrived tuple.
865 cost_qual_eval(&tid_qual_cost, tidquals, root);
867 /* fetch estimated page cost for tablespace containing table */
868 get_tablespace_page_costs(baserel->reltablespace,
869 &spc_random_page_cost,
872 /* disk costs --- assume each tuple on a different page */
873 run_cost += spc_random_page_cost * ntuples;
876 startup_cost += baserel->baserestrictcost.startup +
877 tid_qual_cost.per_tuple;
878 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple -
879 tid_qual_cost.per_tuple;
880 run_cost += cpu_per_tuple * ntuples;
882 path->startup_cost = startup_cost;
883 path->total_cost = startup_cost + run_cost;
888 * Determines and returns the cost of scanning a subquery RTE.
891 cost_subqueryscan(Path *path, RelOptInfo *baserel)
897 /* Should only be applied to base relations that are subqueries */
898 Assert(baserel->relid > 0);
899 Assert(baserel->rtekind == RTE_SUBQUERY);
902 * Cost of path is cost of evaluating the subplan, plus cost of evaluating
903 * any restriction clauses that will be attached to the SubqueryScan node,
904 * plus cpu_tuple_cost to account for selection and projection overhead.
906 path->startup_cost = baserel->subplan->startup_cost;
907 path->total_cost = baserel->subplan->total_cost;
909 startup_cost = baserel->baserestrictcost.startup;
910 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
911 run_cost = cpu_per_tuple * baserel->tuples;
913 path->startup_cost += startup_cost;
914 path->total_cost += startup_cost + run_cost;
919 * Determines and returns the cost of scanning a function RTE.
922 cost_functionscan(Path *path, PlannerInfo *root, RelOptInfo *baserel)
924 Cost startup_cost = 0;
930 /* Should only be applied to base relations that are functions */
931 Assert(baserel->relid > 0);
932 rte = planner_rt_fetch(baserel->relid, root);
933 Assert(rte->rtekind == RTE_FUNCTION);
936 * Estimate costs of executing the function expression.
938 * Currently, nodeFunctionscan.c always executes the function to
939 * completion before returning any rows, and caches the results in a
940 * tuplestore. So the function eval cost is all startup cost, and per-row
943 * XXX in principle we ought to charge tuplestore spill costs if the
944 * number of rows is large. However, given how phony our rowcount
945 * estimates for functions tend to be, there's not a lot of point in that
946 * refinement right now.
948 cost_qual_eval_node(&exprcost, rte->funcexpr, root);
950 startup_cost += exprcost.startup + exprcost.per_tuple;
952 /* Add scanning CPU costs */
953 startup_cost += baserel->baserestrictcost.startup;
954 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
955 run_cost += cpu_per_tuple * baserel->tuples;
957 path->startup_cost = startup_cost;
958 path->total_cost = startup_cost + run_cost;
963 * Determines and returns the cost of scanning a VALUES RTE.
966 cost_valuesscan(Path *path, PlannerInfo *root, RelOptInfo *baserel)
968 Cost startup_cost = 0;
972 /* Should only be applied to base relations that are values lists */
973 Assert(baserel->relid > 0);
974 Assert(baserel->rtekind == RTE_VALUES);
977 * For now, estimate list evaluation cost at one operator eval per list
978 * (probably pretty bogus, but is it worth being smarter?)
980 cpu_per_tuple = cpu_operator_cost;
982 /* Add scanning CPU costs */
983 startup_cost += baserel->baserestrictcost.startup;
984 cpu_per_tuple += cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
985 run_cost += cpu_per_tuple * baserel->tuples;
987 path->startup_cost = startup_cost;
988 path->total_cost = startup_cost + run_cost;
993 * Determines and returns the cost of scanning a CTE RTE.
995 * Note: this is used for both self-reference and regular CTEs; the
996 * possible cost differences are below the threshold of what we could
997 * estimate accurately anyway. Note that the costs of evaluating the
998 * referenced CTE query are added into the final plan as initplan costs,
999 * and should NOT be counted here.
1002 cost_ctescan(Path *path, PlannerInfo *root, RelOptInfo *baserel)
1004 Cost startup_cost = 0;
1008 /* Should only be applied to base relations that are CTEs */
1009 Assert(baserel->relid > 0);
1010 Assert(baserel->rtekind == RTE_CTE);
1012 /* Charge one CPU tuple cost per row for tuplestore manipulation */
1013 cpu_per_tuple = cpu_tuple_cost;
1015 /* Add scanning CPU costs */
1016 startup_cost += baserel->baserestrictcost.startup;
1017 cpu_per_tuple += cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
1018 run_cost += cpu_per_tuple * baserel->tuples;
1020 path->startup_cost = startup_cost;
1021 path->total_cost = startup_cost + run_cost;
1025 * cost_recursive_union
1026 * Determines and returns the cost of performing a recursive union,
1027 * and also the estimated output size.
1029 * We are given Plans for the nonrecursive and recursive terms.
1031 * Note that the arguments and output are Plans, not Paths as in most of
1032 * the rest of this module. That's because we don't bother setting up a
1033 * Path representation for recursive union --- we have only one way to do it.
1036 cost_recursive_union(Plan *runion, Plan *nrterm, Plan *rterm)
1042 /* We probably have decent estimates for the non-recursive term */
1043 startup_cost = nrterm->startup_cost;
1044 total_cost = nrterm->total_cost;
1045 total_rows = nrterm->plan_rows;
1048 * We arbitrarily assume that about 10 recursive iterations will be
1049 * needed, and that we've managed to get a good fix on the cost and output
1050 * size of each one of them. These are mighty shaky assumptions but it's
1051 * hard to see how to do better.
1053 total_cost += 10 * rterm->total_cost;
1054 total_rows += 10 * rterm->plan_rows;
1057 * Also charge cpu_tuple_cost per row to account for the costs of
1058 * manipulating the tuplestores. (We don't worry about possible
1059 * spill-to-disk costs.)
1061 total_cost += cpu_tuple_cost * total_rows;
1063 runion->startup_cost = startup_cost;
1064 runion->total_cost = total_cost;
1065 runion->plan_rows = total_rows;
1066 runion->plan_width = Max(nrterm->plan_width, rterm->plan_width);
1071 * Determines and returns the cost of sorting a relation, including
1072 * the cost of reading the input data.
1074 * If the total volume of data to sort is less than work_mem, we will do
1075 * an in-memory sort, which requires no I/O and about t*log2(t) tuple
1076 * comparisons for t tuples.
1078 * If the total volume exceeds work_mem, we switch to a tape-style merge
1079 * algorithm. There will still be about t*log2(t) tuple comparisons in
1080 * total, but we will also need to write and read each tuple once per
1081 * merge pass. We expect about ceil(logM(r)) merge passes where r is the
1082 * number of initial runs formed and M is the merge order used by tuplesort.c.
1083 * Since the average initial run should be about twice work_mem, we have
1084 * disk traffic = 2 * relsize * ceil(logM(p / (2*work_mem)))
1085 * cpu = comparison_cost * t * log2(t)
1087 * If the sort is bounded (i.e., only the first k result tuples are needed)
1088 * and k tuples can fit into work_mem, we use a heap method that keeps only
1089 * k tuples in the heap; this will require about t*log2(k) tuple comparisons.
1091 * The disk traffic is assumed to be 3/4ths sequential and 1/4th random
1092 * accesses (XXX can't we refine that guess?)
1094 * We charge two operator evals per tuple comparison, which should be in
1095 * the right ballpark in most cases.
1097 * 'pathkeys' is a list of sort keys
1098 * 'input_cost' is the total cost for reading the input data
1099 * 'tuples' is the number of tuples in the relation
1100 * 'width' is the average tuple width in bytes
1101 * 'limit_tuples' is the bound on the number of output tuples; -1 if no bound
1103 * NOTE: some callers currently pass NIL for pathkeys because they
1104 * can't conveniently supply the sort keys. Since this routine doesn't
1105 * currently do anything with pathkeys anyway, that doesn't matter...
1106 * but if it ever does, it should react gracefully to lack of key data.
1107 * (Actually, the thing we'd most likely be interested in is just the number
1108 * of sort keys, which all callers *could* supply.)
1111 cost_sort(Path *path, PlannerInfo *root,
1112 List *pathkeys, Cost input_cost, double tuples, int width,
1113 double limit_tuples)
1115 Cost startup_cost = input_cost;
1117 double input_bytes = relation_byte_size(tuples, width);
1118 double output_bytes;
1119 double output_tuples;
1120 long work_mem_bytes = work_mem * 1024L;
1123 startup_cost += disable_cost;
1126 * We want to be sure the cost of a sort is never estimated as zero, even
1127 * if passed-in tuple count is zero. Besides, mustn't do log(0)...
1132 /* Do we have a useful LIMIT? */
1133 if (limit_tuples > 0 && limit_tuples < tuples)
1135 output_tuples = limit_tuples;
1136 output_bytes = relation_byte_size(output_tuples, width);
1140 output_tuples = tuples;
1141 output_bytes = input_bytes;
1144 if (output_bytes > work_mem_bytes)
1147 * We'll have to use a disk-based sort of all the tuples
1149 double npages = ceil(input_bytes / BLCKSZ);
1150 double nruns = (input_bytes / work_mem_bytes) * 0.5;
1151 double mergeorder = tuplesort_merge_order(work_mem_bytes);
1153 double npageaccesses;
1158 * Assume about two operator evals per tuple comparison and N log2 N
1161 startup_cost += 2.0 * cpu_operator_cost * tuples * LOG2(tuples);
1165 /* Compute logM(r) as log(r) / log(M) */
1166 if (nruns > mergeorder)
1167 log_runs = ceil(log(nruns) / log(mergeorder));
1170 npageaccesses = 2.0 * npages * log_runs;
1171 /* Assume 3/4ths of accesses are sequential, 1/4th are not */
1172 startup_cost += npageaccesses *
1173 (seq_page_cost * 0.75 + random_page_cost * 0.25);
1175 else if (tuples > 2 * output_tuples || input_bytes > work_mem_bytes)
1178 * We'll use a bounded heap-sort keeping just K tuples in memory, for
1179 * a total number of tuple comparisons of N log2 K; but the constant
1180 * factor is a bit higher than for quicksort. Tweak it so that the
1181 * cost curve is continuous at the crossover point.
1183 startup_cost += 2.0 * cpu_operator_cost * tuples * LOG2(2.0 * output_tuples);
1187 /* We'll use plain quicksort on all the input tuples */
1188 startup_cost += 2.0 * cpu_operator_cost * tuples * LOG2(tuples);
1192 * Also charge a small amount (arbitrarily set equal to operator cost) per
1193 * extracted tuple. We don't charge cpu_tuple_cost because a Sort node
1194 * doesn't do qual-checking or projection, so it has less overhead than
1195 * most plan nodes. Note it's correct to use tuples not output_tuples
1196 * here --- the upper LIMIT will pro-rate the run cost so we'd be double
1197 * counting the LIMIT otherwise.
1199 run_cost += cpu_operator_cost * tuples;
1201 path->startup_cost = startup_cost;
1202 path->total_cost = startup_cost + run_cost;
1207 * Determines and returns the cost of materializing a relation, including
1208 * the cost of reading the input data.
1210 * If the total volume of data to materialize exceeds work_mem, we will need
1211 * to write it to disk, so the cost is much higher in that case.
1213 * Note that here we are estimating the costs for the first scan of the
1214 * relation, so the materialization is all overhead --- any savings will
1215 * occur only on rescan, which is estimated in cost_rescan.
1218 cost_material(Path *path,
1219 Cost input_startup_cost, Cost input_total_cost,
1220 double tuples, int width)
1222 Cost startup_cost = input_startup_cost;
1223 Cost run_cost = input_total_cost - input_startup_cost;
1224 double nbytes = relation_byte_size(tuples, width);
1225 long work_mem_bytes = work_mem * 1024L;
1228 * Whether spilling or not, charge 2x cpu_operator_cost per tuple to
1229 * reflect bookkeeping overhead. (This rate must be more than what
1230 * cost_rescan charges for materialize, ie, cpu_operator_cost per tuple;
1231 * if it is exactly the same then there will be a cost tie between
1232 * nestloop with A outer, materialized B inner and nestloop with B outer,
1233 * materialized A inner. The extra cost ensures we'll prefer
1234 * materializing the smaller rel.) Note that this is normally a good deal
1235 * less than cpu_tuple_cost; which is OK because a Material plan node
1236 * doesn't do qual-checking or projection, so it's got less overhead than
1239 run_cost += 2 * cpu_operator_cost * tuples;
1242 * If we will spill to disk, charge at the rate of seq_page_cost per page.
1243 * This cost is assumed to be evenly spread through the plan run phase,
1244 * which isn't exactly accurate but our cost model doesn't allow for
1245 * nonuniform costs within the run phase.
1247 if (nbytes > work_mem_bytes)
1249 double npages = ceil(nbytes / BLCKSZ);
1251 run_cost += seq_page_cost * npages;
1254 path->startup_cost = startup_cost;
1255 path->total_cost = startup_cost + run_cost;
1260 * Determines and returns the cost of performing an Agg plan node,
1261 * including the cost of its input.
1263 * Note: when aggstrategy == AGG_SORTED, caller must ensure that input costs
1264 * are for appropriately-sorted input.
1267 cost_agg(Path *path, PlannerInfo *root,
1268 AggStrategy aggstrategy, int numAggs,
1269 int numGroupCols, double numGroups,
1270 Cost input_startup_cost, Cost input_total_cost,
1271 double input_tuples)
1277 * We charge one cpu_operator_cost per aggregate function per input tuple,
1278 * and another one per output tuple (corresponding to transfn and finalfn
1279 * calls respectively). If we are grouping, we charge an additional
1280 * cpu_operator_cost per grouping column per input tuple for grouping
1283 * We will produce a single output tuple if not grouping, and a tuple per
1284 * group otherwise. We charge cpu_tuple_cost for each output tuple.
1286 * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the
1287 * same total CPU cost, but AGG_SORTED has lower startup cost. If the
1288 * input path is already sorted appropriately, AGG_SORTED should be
1289 * preferred (since it has no risk of memory overflow). This will happen
1290 * as long as the computed total costs are indeed exactly equal --- but if
1291 * there's roundoff error we might do the wrong thing. So be sure that
1292 * the computations below form the same intermediate values in the same
1295 * Note: ideally we should use the pg_proc.procost costs of each
1296 * aggregate's component functions, but for now that seems like an
1297 * excessive amount of work.
1299 if (aggstrategy == AGG_PLAIN)
1301 startup_cost = input_total_cost;
1302 startup_cost += cpu_operator_cost * (input_tuples + 1) * numAggs;
1303 /* we aren't grouping */
1304 total_cost = startup_cost + cpu_tuple_cost;
1306 else if (aggstrategy == AGG_SORTED)
1308 /* Here we are able to deliver output on-the-fly */
1309 startup_cost = input_startup_cost;
1310 total_cost = input_total_cost;
1311 /* calcs phrased this way to match HASHED case, see note above */
1312 total_cost += cpu_operator_cost * input_tuples * numGroupCols;
1313 total_cost += cpu_operator_cost * input_tuples * numAggs;
1314 total_cost += cpu_operator_cost * numGroups * numAggs;
1315 total_cost += cpu_tuple_cost * numGroups;
1319 /* must be AGG_HASHED */
1320 startup_cost = input_total_cost;
1321 startup_cost += cpu_operator_cost * input_tuples * numGroupCols;
1322 startup_cost += cpu_operator_cost * input_tuples * numAggs;
1323 total_cost = startup_cost;
1324 total_cost += cpu_operator_cost * numGroups * numAggs;
1325 total_cost += cpu_tuple_cost * numGroups;
1328 path->startup_cost = startup_cost;
1329 path->total_cost = total_cost;
1334 * Determines and returns the cost of performing a WindowAgg plan node,
1335 * including the cost of its input.
1337 * Input is assumed already properly sorted.
1340 cost_windowagg(Path *path, PlannerInfo *root,
1341 int numWindowFuncs, int numPartCols, int numOrderCols,
1342 Cost input_startup_cost, Cost input_total_cost,
1343 double input_tuples)
1348 startup_cost = input_startup_cost;
1349 total_cost = input_total_cost;
1352 * We charge one cpu_operator_cost per window function per tuple (often a
1353 * drastic underestimate, but without a way to gauge how many tuples the
1354 * window function will fetch, it's hard to do better). We also charge
1355 * cpu_operator_cost per grouping column per tuple for grouping
1356 * comparisons, plus cpu_tuple_cost per tuple for general overhead.
1358 total_cost += cpu_operator_cost * input_tuples * numWindowFuncs;
1359 total_cost += cpu_operator_cost * input_tuples * (numPartCols + numOrderCols);
1360 total_cost += cpu_tuple_cost * input_tuples;
1362 path->startup_cost = startup_cost;
1363 path->total_cost = total_cost;
1368 * Determines and returns the cost of performing a Group plan node,
1369 * including the cost of its input.
1371 * Note: caller must ensure that input costs are for appropriately-sorted
1375 cost_group(Path *path, PlannerInfo *root,
1376 int numGroupCols, double numGroups,
1377 Cost input_startup_cost, Cost input_total_cost,
1378 double input_tuples)
1383 startup_cost = input_startup_cost;
1384 total_cost = input_total_cost;
1387 * Charge one cpu_operator_cost per comparison per input tuple. We assume
1388 * all columns get compared at most of the tuples.
1390 total_cost += cpu_operator_cost * input_tuples * numGroupCols;
1392 path->startup_cost = startup_cost;
1393 path->total_cost = total_cost;
1397 * If a nestloop's inner path is an indexscan, be sure to use its estimated
1398 * output row count, which may be lower than the restriction-clause-only row
1399 * count of its parent. (We don't include this case in the PATH_ROWS macro
1400 * because it applies *only* to a nestloop's inner relation.) We have to
1401 * be prepared to recurse through Append nodes in case of an appendrel.
1404 nestloop_inner_path_rows(Path *path)
1408 if (IsA(path, IndexPath))
1409 result = ((IndexPath *) path)->rows;
1410 else if (IsA(path, BitmapHeapPath))
1411 result = ((BitmapHeapPath *) path)->rows;
1412 else if (IsA(path, AppendPath))
1417 foreach(l, ((AppendPath *) path)->subpaths)
1419 result += nestloop_inner_path_rows((Path *) lfirst(l));
1423 result = PATH_ROWS(path);
1430 * Determines and returns the cost of joining two relations using the
1431 * nested loop algorithm.
1433 * 'path' is already filled in except for the cost fields
1434 * 'sjinfo' is extra info about the join for selectivity estimation
1437 cost_nestloop(NestPath *path, PlannerInfo *root, SpecialJoinInfo *sjinfo)
1439 Path *outer_path = path->outerjoinpath;
1440 Path *inner_path = path->innerjoinpath;
1441 Cost startup_cost = 0;
1443 Cost inner_rescan_start_cost;
1444 Cost inner_rescan_total_cost;
1445 Cost inner_run_cost;
1446 Cost inner_rescan_run_cost;
1448 QualCost restrict_qual_cost;
1449 double outer_path_rows = PATH_ROWS(outer_path);
1450 double inner_path_rows = nestloop_inner_path_rows(inner_path);
1452 Selectivity outer_match_frac;
1453 Selectivity match_count;
1454 bool indexed_join_quals;
1456 if (!enable_nestloop)
1457 startup_cost += disable_cost;
1459 /* estimate costs to rescan the inner relation */
1460 cost_rescan(root, inner_path,
1461 &inner_rescan_start_cost,
1462 &inner_rescan_total_cost);
1464 /* cost of source data */
1467 * NOTE: clearly, we must pay both outer and inner paths' startup_cost
1468 * before we can start returning tuples, so the join's startup cost is
1469 * their sum. We'll also pay the inner path's rescan startup cost
1472 startup_cost += outer_path->startup_cost + inner_path->startup_cost;
1473 run_cost += outer_path->total_cost - outer_path->startup_cost;
1474 if (outer_path_rows > 1)
1475 run_cost += (outer_path_rows - 1) * inner_rescan_start_cost;
1477 inner_run_cost = inner_path->total_cost - inner_path->startup_cost;
1478 inner_rescan_run_cost = inner_rescan_total_cost - inner_rescan_start_cost;
1480 if (adjust_semi_join(root, path, sjinfo,
1483 &indexed_join_quals))
1485 double outer_matched_rows;
1486 Selectivity inner_scan_frac;
1489 * SEMI or ANTI join: executor will stop after first match.
1491 * For an outer-rel row that has at least one match, we can expect the
1492 * inner scan to stop after a fraction 1/(match_count+1) of the inner
1493 * rows, if the matches are evenly distributed. Since they probably
1494 * aren't quite evenly distributed, we apply a fuzz factor of 2.0 to
1495 * that fraction. (If we used a larger fuzz factor, we'd have to
1496 * clamp inner_scan_frac to at most 1.0; but since match_count is at
1497 * least 1, no such clamp is needed now.)
1499 * A complicating factor is that rescans may be cheaper than first
1500 * scans. If we never scan all the way to the end of the inner rel,
1501 * it might be (depending on the plan type) that we'd never pay the
1502 * whole inner first-scan run cost. However it is difficult to
1503 * estimate whether that will happen, so be conservative and always
1504 * charge the whole first-scan cost once.
1506 run_cost += inner_run_cost;
1508 outer_matched_rows = rint(outer_path_rows * outer_match_frac);
1509 inner_scan_frac = 2.0 / (match_count + 1.0);
1511 /* Add inner run cost for additional outer tuples having matches */
1512 if (outer_matched_rows > 1)
1513 run_cost += (outer_matched_rows - 1) * inner_rescan_run_cost * inner_scan_frac;
1515 /* Compute number of tuples processed (not number emitted!) */
1516 ntuples = outer_matched_rows * inner_path_rows * inner_scan_frac;
1519 * For unmatched outer-rel rows, there are two cases. If the inner
1520 * path is an indexscan using all the joinquals as indexquals, then an
1521 * unmatched row results in an indexscan returning no rows, which is
1522 * probably quite cheap. We estimate this case as the same cost to
1523 * return the first tuple of a nonempty scan. Otherwise, the executor
1524 * will have to scan the whole inner rel; not so cheap.
1526 if (indexed_join_quals)
1528 run_cost += (outer_path_rows - outer_matched_rows) *
1529 inner_rescan_run_cost / inner_path_rows;
1532 * We won't be evaluating any quals at all for these rows, so
1533 * don't add them to ntuples.
1538 run_cost += (outer_path_rows - outer_matched_rows) *
1539 inner_rescan_run_cost;
1540 ntuples += (outer_path_rows - outer_matched_rows) *
1546 /* Normal case; we'll scan whole input rel for each outer row */
1547 run_cost += inner_run_cost;
1548 if (outer_path_rows > 1)
1549 run_cost += (outer_path_rows - 1) * inner_rescan_run_cost;
1551 /* Compute number of tuples processed (not number emitted!) */
1552 ntuples = outer_path_rows * inner_path_rows;
1556 cost_qual_eval(&restrict_qual_cost, path->joinrestrictinfo, root);
1557 startup_cost += restrict_qual_cost.startup;
1558 cpu_per_tuple = cpu_tuple_cost + restrict_qual_cost.per_tuple;
1559 run_cost += cpu_per_tuple * ntuples;
1561 path->path.startup_cost = startup_cost;
1562 path->path.total_cost = startup_cost + run_cost;
1567 * Determines and returns the cost of joining two relations using the
1568 * merge join algorithm.
1570 * Unlike other costsize functions, this routine makes one actual decision:
1571 * whether we should materialize the inner path. We do that either because
1572 * the inner path can't support mark/restore, or because it's cheaper to
1573 * use an interposed Material node to handle mark/restore. When the decision
1574 * is cost-based it would be logically cleaner to build and cost two separate
1575 * paths with and without that flag set; but that would require repeating most
1576 * of the calculations here, which are not all that cheap. Since the choice
1577 * will not affect output pathkeys or startup cost, only total cost, there is
1578 * no possibility of wanting to keep both paths. So it seems best to make
1579 * the decision here and record it in the path's materialize_inner field.
1581 * 'path' is already filled in except for the cost fields and materialize_inner
1582 * 'sjinfo' is extra info about the join for selectivity estimation
1584 * Notes: path's mergeclauses should be a subset of the joinrestrictinfo list;
1585 * outersortkeys and innersortkeys are lists of the keys to be used
1586 * to sort the outer and inner relations, or NIL if no explicit
1587 * sort is needed because the source path is already ordered.
1590 cost_mergejoin(MergePath *path, PlannerInfo *root, SpecialJoinInfo *sjinfo)
1592 Path *outer_path = path->jpath.outerjoinpath;
1593 Path *inner_path = path->jpath.innerjoinpath;
1594 List *mergeclauses = path->path_mergeclauses;
1595 List *outersortkeys = path->outersortkeys;
1596 List *innersortkeys = path->innersortkeys;
1597 Cost startup_cost = 0;
1603 QualCost merge_qual_cost;
1604 QualCost qp_qual_cost;
1605 double outer_path_rows = PATH_ROWS(outer_path);
1606 double inner_path_rows = PATH_ROWS(inner_path);
1611 double mergejointuples,
1614 Selectivity outerstartsel,
1618 Path sort_path; /* dummy for result of cost_sort */
1620 /* Protect some assumptions below that rowcounts aren't zero */
1621 if (outer_path_rows <= 0)
1622 outer_path_rows = 1;
1623 if (inner_path_rows <= 0)
1624 inner_path_rows = 1;
1626 if (!enable_mergejoin)
1627 startup_cost += disable_cost;
1630 * Compute cost of the mergequals and qpquals (other restriction clauses)
1633 cost_qual_eval(&merge_qual_cost, mergeclauses, root);
1634 cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
1635 qp_qual_cost.startup -= merge_qual_cost.startup;
1636 qp_qual_cost.per_tuple -= merge_qual_cost.per_tuple;
1639 * Get approx # tuples passing the mergequals. We use approx_tuple_count
1640 * here because we need an estimate done with JOIN_INNER semantics.
1642 mergejointuples = approx_tuple_count(root, &path->jpath, mergeclauses);
1645 * When there are equal merge keys in the outer relation, the mergejoin
1646 * must rescan any matching tuples in the inner relation. This means
1647 * re-fetching inner tuples; we have to estimate how often that happens.
1649 * For regular inner and outer joins, the number of re-fetches can be
1650 * estimated approximately as size of merge join output minus size of
1651 * inner relation. Assume that the distinct key values are 1, 2, ..., and
1652 * denote the number of values of each key in the outer relation as m1,
1653 * m2, ...; in the inner relation, n1, n2, ... Then we have
1655 * size of join = m1 * n1 + m2 * n2 + ...
1657 * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... = m1 *
1658 * n1 + m2 * n2 + ... - (n1 + n2 + ...) = size of join - size of inner
1661 * This equation works correctly for outer tuples having no inner match
1662 * (nk = 0), but not for inner tuples having no outer match (mk = 0); we
1663 * are effectively subtracting those from the number of rescanned tuples,
1664 * when we should not. Can we do better without expensive selectivity
1667 * The whole issue is moot if we are working from a unique-ified outer
1670 if (IsA(outer_path, UniquePath))
1671 rescannedtuples = 0;
1674 rescannedtuples = mergejointuples - inner_path_rows;
1675 /* Must clamp because of possible underestimate */
1676 if (rescannedtuples < 0)
1677 rescannedtuples = 0;
1679 /* We'll inflate various costs this much to account for rescanning */
1680 rescanratio = 1.0 + (rescannedtuples / inner_path_rows);
1683 * A merge join will stop as soon as it exhausts either input stream
1684 * (unless it's an outer join, in which case the outer side has to be
1685 * scanned all the way anyway). Estimate fraction of the left and right
1686 * inputs that will actually need to be scanned. Likewise, we can
1687 * estimate the number of rows that will be skipped before the first join
1688 * pair is found, which should be factored into startup cost. We use only
1689 * the first (most significant) merge clause for this purpose. Since
1690 * mergejoinscansel() is a fairly expensive computation, we cache the
1691 * results in the merge clause RestrictInfo.
1693 if (mergeclauses && path->jpath.jointype != JOIN_FULL)
1695 RestrictInfo *firstclause = (RestrictInfo *) linitial(mergeclauses);
1700 MergeScanSelCache *cache;
1702 /* Get the input pathkeys to determine the sort-order details */
1703 opathkeys = outersortkeys ? outersortkeys : outer_path->pathkeys;
1704 ipathkeys = innersortkeys ? innersortkeys : inner_path->pathkeys;
1707 opathkey = (PathKey *) linitial(opathkeys);
1708 ipathkey = (PathKey *) linitial(ipathkeys);
1709 /* debugging check */
1710 if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
1711 opathkey->pk_strategy != ipathkey->pk_strategy ||
1712 opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
1713 elog(ERROR, "left and right pathkeys do not match in mergejoin");
1715 /* Get the selectivity with caching */
1716 cache = cached_scansel(root, firstclause, opathkey);
1718 if (bms_is_subset(firstclause->left_relids,
1719 outer_path->parent->relids))
1721 /* left side of clause is outer */
1722 outerstartsel = cache->leftstartsel;
1723 outerendsel = cache->leftendsel;
1724 innerstartsel = cache->rightstartsel;
1725 innerendsel = cache->rightendsel;
1729 /* left side of clause is inner */
1730 outerstartsel = cache->rightstartsel;
1731 outerendsel = cache->rightendsel;
1732 innerstartsel = cache->leftstartsel;
1733 innerendsel = cache->leftendsel;
1735 if (path->jpath.jointype == JOIN_LEFT ||
1736 path->jpath.jointype == JOIN_ANTI)
1738 outerstartsel = 0.0;
1741 else if (path->jpath.jointype == JOIN_RIGHT)
1743 innerstartsel = 0.0;
1749 /* cope with clauseless or full mergejoin */
1750 outerstartsel = innerstartsel = 0.0;
1751 outerendsel = innerendsel = 1.0;
1755 * Convert selectivities to row counts. We force outer_rows and
1756 * inner_rows to be at least 1, but the skip_rows estimates can be zero.
1758 outer_skip_rows = rint(outer_path_rows * outerstartsel);
1759 inner_skip_rows = rint(inner_path_rows * innerstartsel);
1760 outer_rows = clamp_row_est(outer_path_rows * outerendsel);
1761 inner_rows = clamp_row_est(inner_path_rows * innerendsel);
1763 Assert(outer_skip_rows <= outer_rows);
1764 Assert(inner_skip_rows <= inner_rows);
1767 * Readjust scan selectivities to account for above rounding. This is
1768 * normally an insignificant effect, but when there are only a few rows in
1769 * the inputs, failing to do this makes for a large percentage error.
1771 outerstartsel = outer_skip_rows / outer_path_rows;
1772 innerstartsel = inner_skip_rows / inner_path_rows;
1773 outerendsel = outer_rows / outer_path_rows;
1774 innerendsel = inner_rows / inner_path_rows;
1776 Assert(outerstartsel <= outerendsel);
1777 Assert(innerstartsel <= innerendsel);
1779 /* cost of source data */
1781 if (outersortkeys) /* do we need to sort outer? */
1783 cost_sort(&sort_path,
1786 outer_path->total_cost,
1788 outer_path->parent->width,
1790 startup_cost += sort_path.startup_cost;
1791 startup_cost += (sort_path.total_cost - sort_path.startup_cost)
1793 run_cost += (sort_path.total_cost - sort_path.startup_cost)
1794 * (outerendsel - outerstartsel);
1798 startup_cost += outer_path->startup_cost;
1799 startup_cost += (outer_path->total_cost - outer_path->startup_cost)
1801 run_cost += (outer_path->total_cost - outer_path->startup_cost)
1802 * (outerendsel - outerstartsel);
1805 if (innersortkeys) /* do we need to sort inner? */
1807 cost_sort(&sort_path,
1810 inner_path->total_cost,
1812 inner_path->parent->width,
1814 startup_cost += sort_path.startup_cost;
1815 startup_cost += (sort_path.total_cost - sort_path.startup_cost)
1817 inner_run_cost = (sort_path.total_cost - sort_path.startup_cost)
1818 * (innerendsel - innerstartsel);
1822 startup_cost += inner_path->startup_cost;
1823 startup_cost += (inner_path->total_cost - inner_path->startup_cost)
1825 inner_run_cost = (inner_path->total_cost - inner_path->startup_cost)
1826 * (innerendsel - innerstartsel);
1830 * Decide whether we want to materialize the inner input to shield it from
1831 * mark/restore and performing re-fetches. Our cost model for regular
1832 * re-fetches is that a re-fetch costs the same as an original fetch,
1833 * which is probably an overestimate; but on the other hand we ignore the
1834 * bookkeeping costs of mark/restore. Not clear if it's worth developing
1835 * a more refined model. So we just need to inflate the inner run cost by
1838 bare_inner_cost = inner_run_cost * rescanratio;
1841 * When we interpose a Material node the re-fetch cost is assumed to be
1842 * just cpu_operator_cost per tuple, independently of the underlying
1843 * plan's cost; and we charge an extra cpu_operator_cost per original
1844 * fetch as well. Note that we're assuming the materialize node will
1845 * never spill to disk, since it only has to remember tuples back to the
1846 * last mark. (If there are a huge number of duplicates, our other cost
1847 * factors will make the path so expensive that it probably won't get
1848 * chosen anyway.) So we don't use cost_rescan here.
1850 * Note: keep this estimate in sync with create_mergejoin_plan's labeling
1851 * of the generated Material node.
1853 mat_inner_cost = inner_run_cost +
1854 cpu_operator_cost * inner_path_rows * rescanratio;
1857 * Prefer materializing if it looks cheaper, unless the user has asked
1858 * to suppress materialization.
1860 if (enable_material && mat_inner_cost < bare_inner_cost)
1861 path->materialize_inner = true;
1864 * Even if materializing doesn't look cheaper, we *must* do it if the
1865 * inner path is to be used directly (without sorting) and it doesn't
1866 * support mark/restore.
1868 * Since the inner side must be ordered, and only Sorts and IndexScans can
1869 * create order to begin with, and they both support mark/restore, you
1870 * might think there's no problem --- but you'd be wrong. Nestloop and
1871 * merge joins can *preserve* the order of their inputs, so they can be
1872 * selected as the input of a mergejoin, and they don't support
1873 * mark/restore at present.
1875 * We don't test the value of enable_material here, because materialization
1876 * is required for correctness in this case, and turning it off does not
1877 * entitle us to deliver an invalid plan.
1879 else if (innersortkeys == NIL &&
1880 !ExecSupportsMarkRestore(inner_path->pathtype))
1881 path->materialize_inner = true;
1884 * Also, force materializing if the inner path is to be sorted and the
1885 * sort is expected to spill to disk. This is because the final merge
1886 * pass can be done on-the-fly if it doesn't have to support mark/restore.
1887 * We don't try to adjust the cost estimates for this consideration,
1890 * Since materialization is a performance optimization in this case, rather
1891 * than necessary for correctness, we skip it if enable_material is off.
1893 else if (enable_material && innersortkeys != NIL &&
1894 relation_byte_size(inner_path_rows, inner_path->parent->width) >
1896 path->materialize_inner = true;
1898 path->materialize_inner = false;
1900 /* Charge the right incremental cost for the chosen case */
1901 if (path->materialize_inner)
1902 run_cost += mat_inner_cost;
1904 run_cost += bare_inner_cost;
1909 * The number of tuple comparisons needed is approximately number of outer
1910 * rows plus number of inner rows plus number of rescanned tuples (can we
1911 * refine this?). At each one, we need to evaluate the mergejoin quals.
1913 startup_cost += merge_qual_cost.startup;
1914 startup_cost += merge_qual_cost.per_tuple *
1915 (outer_skip_rows + inner_skip_rows * rescanratio);
1916 run_cost += merge_qual_cost.per_tuple *
1917 ((outer_rows - outer_skip_rows) +
1918 (inner_rows - inner_skip_rows) * rescanratio);
1921 * For each tuple that gets through the mergejoin proper, we charge
1922 * cpu_tuple_cost plus the cost of evaluating additional restriction
1923 * clauses that are to be applied at the join. (This is pessimistic since
1924 * not all of the quals may get evaluated at each tuple.)
1926 * Note: we could adjust for SEMI/ANTI joins skipping some qual
1927 * evaluations here, but it's probably not worth the trouble.
1929 startup_cost += qp_qual_cost.startup;
1930 cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
1931 run_cost += cpu_per_tuple * mergejointuples;
1933 path->jpath.path.startup_cost = startup_cost;
1934 path->jpath.path.total_cost = startup_cost + run_cost;
1938 * run mergejoinscansel() with caching
1940 static MergeScanSelCache *
1941 cached_scansel(PlannerInfo *root, RestrictInfo *rinfo, PathKey *pathkey)
1943 MergeScanSelCache *cache;
1945 Selectivity leftstartsel,
1949 MemoryContext oldcontext;
1951 /* Do we have this result already? */
1952 foreach(lc, rinfo->scansel_cache)
1954 cache = (MergeScanSelCache *) lfirst(lc);
1955 if (cache->opfamily == pathkey->pk_opfamily &&
1956 cache->strategy == pathkey->pk_strategy &&
1957 cache->nulls_first == pathkey->pk_nulls_first)
1961 /* Nope, do the computation */
1962 mergejoinscansel(root,
1963 (Node *) rinfo->clause,
1964 pathkey->pk_opfamily,
1965 pathkey->pk_strategy,
1966 pathkey->pk_nulls_first,
1972 /* Cache the result in suitably long-lived workspace */
1973 oldcontext = MemoryContextSwitchTo(root->planner_cxt);
1975 cache = (MergeScanSelCache *) palloc(sizeof(MergeScanSelCache));
1976 cache->opfamily = pathkey->pk_opfamily;
1977 cache->strategy = pathkey->pk_strategy;
1978 cache->nulls_first = pathkey->pk_nulls_first;
1979 cache->leftstartsel = leftstartsel;
1980 cache->leftendsel = leftendsel;
1981 cache->rightstartsel = rightstartsel;
1982 cache->rightendsel = rightendsel;
1984 rinfo->scansel_cache = lappend(rinfo->scansel_cache, cache);
1986 MemoryContextSwitchTo(oldcontext);
1993 * Determines and returns the cost of joining two relations using the
1994 * hash join algorithm.
1996 * 'path' is already filled in except for the cost fields
1997 * 'sjinfo' is extra info about the join for selectivity estimation
1999 * Note: path's hashclauses should be a subset of the joinrestrictinfo list
2002 cost_hashjoin(HashPath *path, PlannerInfo *root, SpecialJoinInfo *sjinfo)
2004 Path *outer_path = path->jpath.outerjoinpath;
2005 Path *inner_path = path->jpath.innerjoinpath;
2006 List *hashclauses = path->path_hashclauses;
2007 Cost startup_cost = 0;
2010 QualCost hash_qual_cost;
2011 QualCost qp_qual_cost;
2012 double hashjointuples;
2013 double outer_path_rows = PATH_ROWS(outer_path);
2014 double inner_path_rows = PATH_ROWS(inner_path);
2015 int num_hashclauses = list_length(hashclauses);
2019 double virtualbuckets;
2020 Selectivity innerbucketsize;
2021 Selectivity outer_match_frac;
2022 Selectivity match_count;
2025 if (!enable_hashjoin)
2026 startup_cost += disable_cost;
2029 * Compute cost of the hashquals and qpquals (other restriction clauses)
2032 cost_qual_eval(&hash_qual_cost, hashclauses, root);
2033 cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
2034 qp_qual_cost.startup -= hash_qual_cost.startup;
2035 qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
2037 /* cost of source data */
2038 startup_cost += outer_path->startup_cost;
2039 run_cost += outer_path->total_cost - outer_path->startup_cost;
2040 startup_cost += inner_path->total_cost;
2043 * Cost of computing hash function: must do it once per input tuple. We
2044 * charge one cpu_operator_cost for each column's hash function. Also,
2045 * tack on one cpu_tuple_cost per inner row, to model the costs of
2046 * inserting the row into the hashtable.
2048 * XXX when a hashclause is more complex than a single operator, we really
2049 * should charge the extra eval costs of the left or right side, as
2050 * appropriate, here. This seems more work than it's worth at the moment.
2052 startup_cost += (cpu_operator_cost * num_hashclauses + cpu_tuple_cost)
2054 run_cost += cpu_operator_cost * num_hashclauses * outer_path_rows;
2057 * Get hash table size that executor would use for inner relation.
2059 * XXX for the moment, always assume that skew optimization will be
2060 * performed. As long as SKEW_WORK_MEM_PERCENT is small, it's not worth
2061 * trying to determine that for sure.
2063 * XXX at some point it might be interesting to try to account for skew
2064 * optimization in the cost estimate, but for now, we don't.
2066 ExecChooseHashTableSize(inner_path_rows,
2067 inner_path->parent->width,
2072 virtualbuckets = (double) numbuckets *(double) numbatches;
2074 /* mark the path with estimated # of batches */
2075 path->num_batches = numbatches;
2078 * Determine bucketsize fraction for inner relation. We use the smallest
2079 * bucketsize estimated for any individual hashclause; this is undoubtedly
2082 * BUT: if inner relation has been unique-ified, we can assume it's good
2083 * for hashing. This is important both because it's the right answer, and
2084 * because we avoid contaminating the cache with a value that's wrong for
2085 * non-unique-ified paths.
2087 if (IsA(inner_path, UniquePath))
2088 innerbucketsize = 1.0 / virtualbuckets;
2091 innerbucketsize = 1.0;
2092 foreach(hcl, hashclauses)
2094 RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(hcl);
2095 Selectivity thisbucketsize;
2097 Assert(IsA(restrictinfo, RestrictInfo));
2100 * First we have to figure out which side of the hashjoin clause
2101 * is the inner side.
2103 * Since we tend to visit the same clauses over and over when
2104 * planning a large query, we cache the bucketsize estimate in the
2105 * RestrictInfo node to avoid repeated lookups of statistics.
2107 if (bms_is_subset(restrictinfo->right_relids,
2108 inner_path->parent->relids))
2110 /* righthand side is inner */
2111 thisbucketsize = restrictinfo->right_bucketsize;
2112 if (thisbucketsize < 0)
2114 /* not cached yet */
2116 estimate_hash_bucketsize(root,
2117 get_rightop(restrictinfo->clause),
2119 restrictinfo->right_bucketsize = thisbucketsize;
2124 Assert(bms_is_subset(restrictinfo->left_relids,
2125 inner_path->parent->relids));
2126 /* lefthand side is inner */
2127 thisbucketsize = restrictinfo->left_bucketsize;
2128 if (thisbucketsize < 0)
2130 /* not cached yet */
2132 estimate_hash_bucketsize(root,
2133 get_leftop(restrictinfo->clause),
2135 restrictinfo->left_bucketsize = thisbucketsize;
2139 if (innerbucketsize > thisbucketsize)
2140 innerbucketsize = thisbucketsize;
2145 * If inner relation is too big then we will need to "batch" the join,
2146 * which implies writing and reading most of the tuples to disk an extra
2147 * time. Charge seq_page_cost per page, since the I/O should be nice and
2148 * sequential. Writing the inner rel counts as startup cost, all the rest
2153 double outerpages = page_size(outer_path_rows,
2154 outer_path->parent->width);
2155 double innerpages = page_size(inner_path_rows,
2156 inner_path->parent->width);
2158 startup_cost += seq_page_cost * innerpages;
2159 run_cost += seq_page_cost * (innerpages + 2 * outerpages);
2164 if (adjust_semi_join(root, &path->jpath, sjinfo,
2169 double outer_matched_rows;
2170 Selectivity inner_scan_frac;
2173 * SEMI or ANTI join: executor will stop after first match.
2175 * For an outer-rel row that has at least one match, we can expect the
2176 * bucket scan to stop after a fraction 1/(match_count+1) of the
2177 * bucket's rows, if the matches are evenly distributed. Since they
2178 * probably aren't quite evenly distributed, we apply a fuzz factor of
2179 * 2.0 to that fraction. (If we used a larger fuzz factor, we'd have
2180 * to clamp inner_scan_frac to at most 1.0; but since match_count is
2181 * at least 1, no such clamp is needed now.)
2183 outer_matched_rows = rint(outer_path_rows * outer_match_frac);
2184 inner_scan_frac = 2.0 / (match_count + 1.0);
2186 startup_cost += hash_qual_cost.startup;
2187 run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
2188 clamp_row_est(inner_path_rows * innerbucketsize * inner_scan_frac) * 0.5;
2191 * For unmatched outer-rel rows, the picture is quite a lot different.
2192 * In the first place, there is no reason to assume that these rows
2193 * preferentially hit heavily-populated buckets; instead assume they
2194 * are uncorrelated with the inner distribution and so they see an
2195 * average bucket size of inner_path_rows / virtualbuckets. In the
2196 * second place, it seems likely that they will have few if any exact
2197 * hash-code matches and so very few of the tuples in the bucket will
2198 * actually require eval of the hash quals. We don't have any good
2199 * way to estimate how many will, but for the moment assume that the
2200 * effective cost per bucket entry is one-tenth what it is for
2203 run_cost += hash_qual_cost.per_tuple *
2204 (outer_path_rows - outer_matched_rows) *
2205 clamp_row_est(inner_path_rows / virtualbuckets) * 0.05;
2207 /* Get # of tuples that will pass the basic join */
2208 if (path->jpath.jointype == JOIN_SEMI)
2209 hashjointuples = outer_matched_rows;
2211 hashjointuples = outer_path_rows - outer_matched_rows;
2216 * The number of tuple comparisons needed is the number of outer
2217 * tuples times the typical number of tuples in a hash bucket, which
2218 * is the inner relation size times its bucketsize fraction. At each
2219 * one, we need to evaluate the hashjoin quals. But actually,
2220 * charging the full qual eval cost at each tuple is pessimistic,
2221 * since we don't evaluate the quals unless the hash values match
2222 * exactly. For lack of a better idea, halve the cost estimate to
2225 startup_cost += hash_qual_cost.startup;
2226 run_cost += hash_qual_cost.per_tuple * outer_path_rows *
2227 clamp_row_est(inner_path_rows * innerbucketsize) * 0.5;
2230 * Get approx # tuples passing the hashquals. We use
2231 * approx_tuple_count here because we need an estimate done with
2232 * JOIN_INNER semantics.
2234 hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
2238 * For each tuple that gets through the hashjoin proper, we charge
2239 * cpu_tuple_cost plus the cost of evaluating additional restriction
2240 * clauses that are to be applied at the join. (This is pessimistic since
2241 * not all of the quals may get evaluated at each tuple.)
2243 startup_cost += qp_qual_cost.startup;
2244 cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
2245 run_cost += cpu_per_tuple * hashjointuples;
2247 path->jpath.path.startup_cost = startup_cost;
2248 path->jpath.path.total_cost = startup_cost + run_cost;
2254 * Figure the costs for a SubPlan (or initplan).
2256 * Note: we could dig the subplan's Plan out of the root list, but in practice
2257 * all callers have it handy already, so we make them pass it.
2260 cost_subplan(PlannerInfo *root, SubPlan *subplan, Plan *plan)
2264 /* Figure any cost for evaluating the testexpr */
2265 cost_qual_eval(&sp_cost,
2266 make_ands_implicit((Expr *) subplan->testexpr),
2269 if (subplan->useHashTable)
2272 * If we are using a hash table for the subquery outputs, then the
2273 * cost of evaluating the query is a one-time cost. We charge one
2274 * cpu_operator_cost per tuple for the work of loading the hashtable,
2277 sp_cost.startup += plan->total_cost +
2278 cpu_operator_cost * plan->plan_rows;
2281 * The per-tuple costs include the cost of evaluating the lefthand
2282 * expressions, plus the cost of probing the hashtable. We already
2283 * accounted for the lefthand expressions as part of the testexpr, and
2284 * will also have counted one cpu_operator_cost for each comparison
2285 * operator. That is probably too low for the probing cost, but it's
2286 * hard to make a better estimate, so live with it for now.
2292 * Otherwise we will be rescanning the subplan output on each
2293 * evaluation. We need to estimate how much of the output we will
2294 * actually need to scan. NOTE: this logic should agree with the
2295 * tuple_fraction estimates used by make_subplan() in
2298 Cost plan_run_cost = plan->total_cost - plan->startup_cost;
2300 if (subplan->subLinkType == EXISTS_SUBLINK)
2302 /* we only need to fetch 1 tuple */
2303 sp_cost.per_tuple += plan_run_cost / plan->plan_rows;
2305 else if (subplan->subLinkType == ALL_SUBLINK ||
2306 subplan->subLinkType == ANY_SUBLINK)
2308 /* assume we need 50% of the tuples */
2309 sp_cost.per_tuple += 0.50 * plan_run_cost;
2310 /* also charge a cpu_operator_cost per row examined */
2311 sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
2315 /* assume we need all tuples */
2316 sp_cost.per_tuple += plan_run_cost;
2320 * Also account for subplan's startup cost. If the subplan is
2321 * uncorrelated or undirect correlated, AND its topmost node is one
2322 * that materializes its output, assume that we'll only need to pay
2323 * its startup cost once; otherwise assume we pay the startup cost
2326 if (subplan->parParam == NIL &&
2327 ExecMaterializesOutput(nodeTag(plan)))
2328 sp_cost.startup += plan->startup_cost;
2330 sp_cost.per_tuple += plan->startup_cost;
2333 subplan->startup_cost = sp_cost.startup;
2334 subplan->per_call_cost = sp_cost.per_tuple;
2340 * Given a finished Path, estimate the costs of rescanning it after
2341 * having done so the first time. For some Path types a rescan is
2342 * cheaper than an original scan (if no parameters change), and this
2343 * function embodies knowledge about that. The default is to return
2344 * the same costs stored in the Path. (Note that the cost estimates
2345 * actually stored in Paths are always for first scans.)
2347 * This function is not currently intended to model effects such as rescans
2348 * being cheaper due to disk block caching; what we are concerned with is
2349 * plan types wherein the executor caches results explicitly, or doesn't
2350 * redo startup calculations, etc.
2353 cost_rescan(PlannerInfo *root, Path *path,
2354 Cost *rescan_startup_cost, /* output parameters */
2355 Cost *rescan_total_cost)
2357 switch (path->pathtype)
2359 case T_FunctionScan:
2362 * Currently, nodeFunctionscan.c always executes the function to
2363 * completion before returning any rows, and caches the results in
2364 * a tuplestore. So the function eval cost is all startup cost
2365 * and isn't paid over again on rescans. However, all run costs
2366 * will be paid over again.
2368 *rescan_startup_cost = 0;
2369 *rescan_total_cost = path->total_cost - path->startup_cost;
2374 * Assume that all of the startup cost represents hash table
2375 * building, which we won't have to do over.
2377 *rescan_startup_cost = 0;
2378 *rescan_total_cost = path->total_cost - path->startup_cost;
2381 case T_WorkTableScan:
2384 * These plan types materialize their final result in a
2385 * tuplestore or tuplesort object. So the rescan cost is only
2386 * cpu_tuple_cost per tuple, unless the result is large enough
2389 Cost run_cost = cpu_tuple_cost * path->parent->rows;
2390 double nbytes = relation_byte_size(path->parent->rows,
2391 path->parent->width);
2392 long work_mem_bytes = work_mem * 1024L;
2394 if (nbytes > work_mem_bytes)
2396 /* It will spill, so account for re-read cost */
2397 double npages = ceil(nbytes / BLCKSZ);
2399 run_cost += seq_page_cost * npages;
2401 *rescan_startup_cost = 0;
2402 *rescan_total_cost = run_cost;
2409 * These plan types not only materialize their results, but do
2410 * not implement qual filtering or projection. So they are
2411 * even cheaper to rescan than the ones above. We charge only
2412 * cpu_operator_cost per tuple. (Note: keep that in sync with
2413 * the run_cost charge in cost_sort, and also see comments in
2414 * cost_material before you change it.)
2416 Cost run_cost = cpu_operator_cost * path->parent->rows;
2417 double nbytes = relation_byte_size(path->parent->rows,
2418 path->parent->width);
2419 long work_mem_bytes = work_mem * 1024L;
2421 if (nbytes > work_mem_bytes)
2423 /* It will spill, so account for re-read cost */
2424 double npages = ceil(nbytes / BLCKSZ);
2426 run_cost += seq_page_cost * npages;
2428 *rescan_startup_cost = 0;
2429 *rescan_total_cost = run_cost;
2433 *rescan_startup_cost = path->startup_cost;
2434 *rescan_total_cost = path->total_cost;
2442 * Estimate the CPU costs of evaluating a WHERE clause.
2443 * The input can be either an implicitly-ANDed list of boolean
2444 * expressions, or a list of RestrictInfo nodes. (The latter is
2445 * preferred since it allows caching of the results.)
2446 * The result includes both a one-time (startup) component,
2447 * and a per-evaluation component.
2450 cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
2452 cost_qual_eval_context context;
2455 context.root = root;
2456 context.total.startup = 0;
2457 context.total.per_tuple = 0;
2459 /* We don't charge any cost for the implicit ANDing at top level ... */
2463 Node *qual = (Node *) lfirst(l);
2465 cost_qual_eval_walker(qual, &context);
2468 *cost = context.total;
2472 * cost_qual_eval_node
2473 * As above, for a single RestrictInfo or expression.
2476 cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
2478 cost_qual_eval_context context;
2480 context.root = root;
2481 context.total.startup = 0;
2482 context.total.per_tuple = 0;
2484 cost_qual_eval_walker(qual, &context);
2486 *cost = context.total;
2490 cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
2496 * RestrictInfo nodes contain an eval_cost field reserved for this
2497 * routine's use, so that it's not necessary to evaluate the qual clause's
2498 * cost more than once. If the clause's cost hasn't been computed yet,
2499 * the field's startup value will contain -1.
2501 if (IsA(node, RestrictInfo))
2503 RestrictInfo *rinfo = (RestrictInfo *) node;
2505 if (rinfo->eval_cost.startup < 0)
2507 cost_qual_eval_context locContext;
2509 locContext.root = context->root;
2510 locContext.total.startup = 0;
2511 locContext.total.per_tuple = 0;
2514 * For an OR clause, recurse into the marked-up tree so that we
2515 * set the eval_cost for contained RestrictInfos too.
2517 if (rinfo->orclause)
2518 cost_qual_eval_walker((Node *) rinfo->orclause, &locContext);
2520 cost_qual_eval_walker((Node *) rinfo->clause, &locContext);
2523 * If the RestrictInfo is marked pseudoconstant, it will be tested
2524 * only once, so treat its cost as all startup cost.
2526 if (rinfo->pseudoconstant)
2528 /* count one execution during startup */
2529 locContext.total.startup += locContext.total.per_tuple;
2530 locContext.total.per_tuple = 0;
2532 rinfo->eval_cost = locContext.total;
2534 context->total.startup += rinfo->eval_cost.startup;
2535 context->total.per_tuple += rinfo->eval_cost.per_tuple;
2536 /* do NOT recurse into children */
2541 * For each operator or function node in the given tree, we charge the
2542 * estimated execution cost given by pg_proc.procost (remember to multiply
2543 * this by cpu_operator_cost).
2545 * Vars and Consts are charged zero, and so are boolean operators (AND,
2546 * OR, NOT). Simplistic, but a lot better than no model at all.
2548 * Note that Aggref and WindowFunc nodes are (and should be) treated like
2549 * Vars --- whatever execution cost they have is absorbed into
2550 * plan-node-specific costing. As far as expression evaluation is
2551 * concerned they're just like Vars.
2553 * Should we try to account for the possibility of short-circuit
2554 * evaluation of AND/OR? Probably *not*, because that would make the
2555 * results depend on the clause ordering, and we are not in any position
2556 * to expect that the current ordering of the clauses is the one that's
2557 * going to end up being used. (Is it worth applying order_qual_clauses
2558 * much earlier in the planning process to fix this?)
2560 if (IsA(node, FuncExpr))
2562 context->total.per_tuple +=
2563 get_func_cost(((FuncExpr *) node)->funcid) * cpu_operator_cost;
2565 else if (IsA(node, OpExpr) ||
2566 IsA(node, DistinctExpr) ||
2567 IsA(node, NullIfExpr))
2569 /* rely on struct equivalence to treat these all alike */
2570 set_opfuncid((OpExpr *) node);
2571 context->total.per_tuple +=
2572 get_func_cost(((OpExpr *) node)->opfuncid) * cpu_operator_cost;
2574 else if (IsA(node, ScalarArrayOpExpr))
2577 * Estimate that the operator will be applied to about half of the
2578 * array elements before the answer is determined.
2580 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
2581 Node *arraynode = (Node *) lsecond(saop->args);
2583 set_sa_opfuncid(saop);
2584 context->total.per_tuple += get_func_cost(saop->opfuncid) *
2585 cpu_operator_cost * estimate_array_length(arraynode) * 0.5;
2587 else if (IsA(node, CoerceViaIO))
2589 CoerceViaIO *iocoerce = (CoerceViaIO *) node;
2594 /* check the result type's input function */
2595 getTypeInputInfo(iocoerce->resulttype,
2596 &iofunc, &typioparam);
2597 context->total.per_tuple += get_func_cost(iofunc) * cpu_operator_cost;
2598 /* check the input type's output function */
2599 getTypeOutputInfo(exprType((Node *) iocoerce->arg),
2600 &iofunc, &typisvarlena);
2601 context->total.per_tuple += get_func_cost(iofunc) * cpu_operator_cost;
2603 else if (IsA(node, ArrayCoerceExpr))
2605 ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
2606 Node *arraynode = (Node *) acoerce->arg;
2608 if (OidIsValid(acoerce->elemfuncid))
2609 context->total.per_tuple += get_func_cost(acoerce->elemfuncid) *
2610 cpu_operator_cost * estimate_array_length(arraynode);
2612 else if (IsA(node, RowCompareExpr))
2614 /* Conservatively assume we will check all the columns */
2615 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
2618 foreach(lc, rcexpr->opnos)
2620 Oid opid = lfirst_oid(lc);
2622 context->total.per_tuple += get_func_cost(get_opcode(opid)) *
2626 else if (IsA(node, CurrentOfExpr))
2628 /* Report high cost to prevent selection of anything but TID scan */
2629 context->total.startup += disable_cost;
2631 else if (IsA(node, SubLink))
2633 /* This routine should not be applied to un-planned expressions */
2634 elog(ERROR, "cannot handle unplanned sub-select");
2636 else if (IsA(node, SubPlan))
2639 * A subplan node in an expression typically indicates that the
2640 * subplan will be executed on each evaluation, so charge accordingly.
2641 * (Sub-selects that can be executed as InitPlans have already been
2642 * removed from the expression.)
2644 SubPlan *subplan = (SubPlan *) node;
2646 context->total.startup += subplan->startup_cost;
2647 context->total.per_tuple += subplan->per_call_cost;
2650 * We don't want to recurse into the testexpr, because it was already
2651 * counted in the SubPlan node's costs. So we're done.
2655 else if (IsA(node, AlternativeSubPlan))
2658 * Arbitrarily use the first alternative plan for costing. (We should
2659 * certainly only include one alternative, and we don't yet have
2660 * enough information to know which one the executor is most likely to
2663 AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
2665 return cost_qual_eval_walker((Node *) linitial(asplan->subplans),
2669 /* recurse into children */
2670 return expression_tree_walker(node, cost_qual_eval_walker,
2677 * Estimate how much of the inner input a SEMI or ANTI join
2678 * can be expected to scan.
2680 * In a hash or nestloop SEMI/ANTI join, the executor will stop scanning
2681 * inner rows as soon as it finds a match to the current outer row.
2682 * We should therefore adjust some of the cost components for this effect.
2683 * This function computes some estimates needed for these adjustments.
2685 * 'path' is already filled in except for the cost fields
2686 * 'sjinfo' is extra info about the join for selectivity estimation
2688 * Returns TRUE if this is a SEMI or ANTI join, FALSE if not.
2690 * Output parameters (set only in TRUE-result case):
2691 * *outer_match_frac is set to the fraction of the outer tuples that are
2692 * expected to have at least one match.
2693 * *match_count is set to the average number of matches expected for
2694 * outer tuples that have at least one match.
2695 * *indexed_join_quals is set to TRUE if all the joinquals are used as
2696 * inner index quals, FALSE if not.
2698 * indexed_join_quals can be passed as NULL if that information is not
2699 * relevant (it is only useful for the nestloop case).
2702 adjust_semi_join(PlannerInfo *root, JoinPath *path, SpecialJoinInfo *sjinfo,
2703 Selectivity *outer_match_frac,
2704 Selectivity *match_count,
2705 bool *indexed_join_quals)
2707 JoinType jointype = path->jointype;
2710 Selectivity avgmatch;
2711 SpecialJoinInfo norm_sjinfo;
2715 /* Fall out if it's not JOIN_SEMI or JOIN_ANTI */
2716 if (jointype != JOIN_SEMI && jointype != JOIN_ANTI)
2720 * Note: it's annoying to repeat this selectivity estimation on each call,
2721 * when the joinclause list will be the same for all path pairs
2722 * implementing a given join. clausesel.c will save us from the worst
2723 * effects of this by caching at the RestrictInfo level; but perhaps it'd
2724 * be worth finding a way to cache the results at a higher level.
2728 * In an ANTI join, we must ignore clauses that are "pushed down", since
2729 * those won't affect the match logic. In a SEMI join, we do not
2730 * distinguish joinquals from "pushed down" quals, so just use the whole
2731 * restrictinfo list.
2733 if (jointype == JOIN_ANTI)
2736 foreach(l, path->joinrestrictinfo)
2738 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
2740 Assert(IsA(rinfo, RestrictInfo));
2741 if (!rinfo->is_pushed_down)
2742 joinquals = lappend(joinquals, rinfo);
2746 joinquals = path->joinrestrictinfo;
2749 * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
2751 jselec = clauselist_selectivity(root,
2758 * Also get the normal inner-join selectivity of the join clauses.
2760 norm_sjinfo.type = T_SpecialJoinInfo;
2761 norm_sjinfo.min_lefthand = path->outerjoinpath->parent->relids;
2762 norm_sjinfo.min_righthand = path->innerjoinpath->parent->relids;
2763 norm_sjinfo.syn_lefthand = path->outerjoinpath->parent->relids;
2764 norm_sjinfo.syn_righthand = path->innerjoinpath->parent->relids;
2765 norm_sjinfo.jointype = JOIN_INNER;
2766 /* we don't bother trying to make the remaining fields valid */
2767 norm_sjinfo.lhs_strict = false;
2768 norm_sjinfo.delay_upper_joins = false;
2769 norm_sjinfo.join_quals = NIL;
2771 nselec = clauselist_selectivity(root,
2777 /* Avoid leaking a lot of ListCells */
2778 if (jointype == JOIN_ANTI)
2779 list_free(joinquals);
2782 * jselec can be interpreted as the fraction of outer-rel rows that have
2783 * any matches (this is true for both SEMI and ANTI cases). And nselec is
2784 * the fraction of the Cartesian product that matches. So, the average
2785 * number of matches for each outer-rel row that has at least one match is
2786 * nselec * inner_rows / jselec.
2788 * Note: it is correct to use the inner rel's "rows" count here, not
2789 * PATH_ROWS(), even if the inner path under consideration is an inner
2790 * indexscan. This is because we have included all the join clauses in
2791 * the selectivity estimate, even ones used in an inner indexscan.
2793 if (jselec > 0) /* protect against zero divide */
2795 avgmatch = nselec * path->innerjoinpath->parent->rows / jselec;
2796 /* Clamp to sane range */
2797 avgmatch = Max(1.0, avgmatch);
2802 *outer_match_frac = jselec;
2803 *match_count = avgmatch;
2806 * If requested, check whether the inner path uses all the joinquals as
2807 * indexquals. (If that's true, we can assume that an unmatched outer
2808 * tuple is cheap to process, whereas otherwise it's probably expensive.)
2810 if (indexed_join_quals)
2814 nrclauses = select_nonredundant_join_clauses(root,
2815 path->joinrestrictinfo,
2816 path->innerjoinpath);
2817 *indexed_join_quals = (nrclauses == NIL);
2825 * approx_tuple_count
2826 * Quick-and-dirty estimation of the number of join rows passing
2827 * a set of qual conditions.
2829 * The quals can be either an implicitly-ANDed list of boolean expressions,
2830 * or a list of RestrictInfo nodes (typically the latter).
2832 * We intentionally compute the selectivity under JOIN_INNER rules, even
2833 * if it's some type of outer join. This is appropriate because we are
2834 * trying to figure out how many tuples pass the initial merge or hash
2837 * This is quick-and-dirty because we bypass clauselist_selectivity, and
2838 * simply multiply the independent clause selectivities together. Now
2839 * clauselist_selectivity often can't do any better than that anyhow, but
2840 * for some situations (such as range constraints) it is smarter. However,
2841 * we can't effectively cache the results of clauselist_selectivity, whereas
2842 * the individual clause selectivities can be and are cached.
2844 * Since we are only using the results to estimate how many potential
2845 * output tuples are generated and passed through qpqual checking, it
2846 * seems OK to live with the approximation.
2849 approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
2852 double outer_tuples = path->outerjoinpath->parent->rows;
2853 double inner_tuples = path->innerjoinpath->parent->rows;
2854 SpecialJoinInfo sjinfo;
2855 Selectivity selec = 1.0;
2859 * Make up a SpecialJoinInfo for JOIN_INNER semantics.
2861 sjinfo.type = T_SpecialJoinInfo;
2862 sjinfo.min_lefthand = path->outerjoinpath->parent->relids;
2863 sjinfo.min_righthand = path->innerjoinpath->parent->relids;
2864 sjinfo.syn_lefthand = path->outerjoinpath->parent->relids;
2865 sjinfo.syn_righthand = path->innerjoinpath->parent->relids;
2866 sjinfo.jointype = JOIN_INNER;
2867 /* we don't bother trying to make the remaining fields valid */
2868 sjinfo.lhs_strict = false;
2869 sjinfo.delay_upper_joins = false;
2870 sjinfo.join_quals = NIL;
2872 /* Get the approximate selectivity */
2875 Node *qual = (Node *) lfirst(l);
2877 /* Note that clause_selectivity will be able to cache its result */
2878 selec *= clause_selectivity(root, qual, 0, JOIN_INNER, &sjinfo);
2881 /* Apply it to the input relation sizes */
2882 tuples = selec * outer_tuples * inner_tuples;
2884 return clamp_row_est(tuples);
2889 * set_baserel_size_estimates
2890 * Set the size estimates for the given base relation.
2892 * The rel's targetlist and restrictinfo list must have been constructed
2895 * We set the following fields of the rel node:
2896 * rows: the estimated number of output tuples (after applying
2897 * restriction clauses).
2898 * width: the estimated average output tuple width in bytes.
2899 * baserestrictcost: estimated cost of evaluating baserestrictinfo clauses.
2902 set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
2906 /* Should only be applied to base relations */
2907 Assert(rel->relid > 0);
2909 nrows = rel->tuples *
2910 clauselist_selectivity(root,
2911 rel->baserestrictinfo,
2916 rel->rows = clamp_row_est(nrows);
2918 cost_qual_eval(&rel->baserestrictcost, rel->baserestrictinfo, root);
2920 set_rel_width(root, rel);
2924 * set_joinrel_size_estimates
2925 * Set the size estimates for the given join relation.
2927 * The rel's targetlist must have been constructed already, and a
2928 * restriction clause list that matches the given component rels must
2931 * Since there is more than one way to make a joinrel for more than two
2932 * base relations, the results we get here could depend on which component
2933 * rel pair is provided. In theory we should get the same answers no matter
2934 * which pair is provided; in practice, since the selectivity estimation
2935 * routines don't handle all cases equally well, we might not. But there's
2936 * not much to be done about it. (Would it make sense to repeat the
2937 * calculations for each pair of input rels that's encountered, and somehow
2938 * average the results? Probably way more trouble than it's worth.)
2940 * We set only the rows field here. The width field was already set by
2941 * build_joinrel_tlist, and baserestrictcost is not used for join rels.
2944 set_joinrel_size_estimates(PlannerInfo *root, RelOptInfo *rel,
2945 RelOptInfo *outer_rel,
2946 RelOptInfo *inner_rel,
2947 SpecialJoinInfo *sjinfo,
2950 JoinType jointype = sjinfo->jointype;
2956 * Compute joinclause selectivity. Note that we are only considering
2957 * clauses that become restriction clauses at this join level; we are not
2958 * double-counting them because they were not considered in estimating the
2959 * sizes of the component rels.
2961 * For an outer join, we have to distinguish the selectivity of the join's
2962 * own clauses (JOIN/ON conditions) from any clauses that were "pushed
2963 * down". For inner joins we just count them all as joinclauses.
2965 if (IS_OUTER_JOIN(jointype))
2967 List *joinquals = NIL;
2968 List *pushedquals = NIL;
2971 /* Grovel through the clauses to separate into two lists */
2972 foreach(l, restrictlist)
2974 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
2976 Assert(IsA(rinfo, RestrictInfo));
2977 if (rinfo->is_pushed_down)
2978 pushedquals = lappend(pushedquals, rinfo);
2980 joinquals = lappend(joinquals, rinfo);
2983 /* Get the separate selectivities */
2984 jselec = clauselist_selectivity(root,
2989 pselec = clauselist_selectivity(root,
2995 /* Avoid leaking a lot of ListCells */
2996 list_free(joinquals);
2997 list_free(pushedquals);
3001 jselec = clauselist_selectivity(root,
3006 pselec = 0.0; /* not used, keep compiler quiet */
3010 * Basically, we multiply size of Cartesian product by selectivity.
3012 * If we are doing an outer join, take that into account: the joinqual
3013 * selectivity has to be clamped using the knowledge that the output must
3014 * be at least as large as the non-nullable input. However, any
3015 * pushed-down quals are applied after the outer join, so their
3016 * selectivity applies fully.
3018 * For JOIN_SEMI and JOIN_ANTI, the selectivity is defined as the fraction
3019 * of LHS rows that have matches, and we apply that straightforwardly.
3024 nrows = outer_rel->rows * inner_rel->rows * jselec;
3027 nrows = outer_rel->rows * inner_rel->rows * jselec;
3028 if (nrows < outer_rel->rows)
3029 nrows = outer_rel->rows;
3033 nrows = outer_rel->rows * inner_rel->rows * jselec;
3034 if (nrows < outer_rel->rows)
3035 nrows = outer_rel->rows;
3036 if (nrows < inner_rel->rows)
3037 nrows = inner_rel->rows;
3041 nrows = outer_rel->rows * jselec;
3042 /* pselec not used */
3045 nrows = outer_rel->rows * (1.0 - jselec);
3049 /* other values not expected here */
3050 elog(ERROR, "unrecognized join type: %d", (int) jointype);
3051 nrows = 0; /* keep compiler quiet */
3055 rel->rows = clamp_row_est(nrows);
3059 * set_function_size_estimates
3060 * Set the size estimates for a base relation that is a function call.
3062 * The rel's targetlist and restrictinfo list must have been constructed
3065 * We set the same fields as set_baserel_size_estimates.
3068 set_function_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3072 /* Should only be applied to base relations that are functions */
3073 Assert(rel->relid > 0);
3074 rte = planner_rt_fetch(rel->relid, root);
3075 Assert(rte->rtekind == RTE_FUNCTION);
3077 /* Estimate number of rows the function itself will return */
3078 rel->tuples = clamp_row_est(expression_returns_set_rows(rte->funcexpr));
3080 /* Now estimate number of output rows, etc */
3081 set_baserel_size_estimates(root, rel);
3085 * set_values_size_estimates
3086 * Set the size estimates for a base relation that is a values list.
3088 * The rel's targetlist and restrictinfo list must have been constructed
3091 * We set the same fields as set_baserel_size_estimates.
3094 set_values_size_estimates(PlannerInfo *root, RelOptInfo *rel)
3098 /* Should only be applied to base relations that are values lists */
3099 Assert(rel->relid > 0);
3100 rte = planner_rt_fetch(rel->relid, root);
3101 Assert(rte->rtekind == RTE_VALUES);
3104 * Estimate number of rows the values list will return. We know this
3105 * precisely based on the list length (well, barring set-returning
3106 * functions in list items, but that's a refinement not catered for
3107 * anywhere else either).
3109 rel->tuples = list_length(rte->values_lists);
3111 /* Now estimate number of output rows, etc */
3112 set_baserel_size_estimates(root, rel);
3116 * set_cte_size_estimates
3117 * Set the size estimates for a base relation that is a CTE reference.
3119 * The rel's targetlist and restrictinfo list must have been constructed
3120 * already, and we need the completed plan for the CTE (if a regular CTE)
3121 * or the non-recursive term (if a self-reference).
3123 * We set the same fields as set_baserel_size_estimates.
3126 set_cte_size_estimates(PlannerInfo *root, RelOptInfo *rel, Plan *cteplan)
3130 /* Should only be applied to base relations that are CTE references */
3131 Assert(rel->relid > 0);
3132 rte = planner_rt_fetch(rel->relid, root);
3133 Assert(rte->rtekind == RTE_CTE);
3135 if (rte->self_reference)
3138 * In a self-reference, arbitrarily assume the average worktable size
3139 * is about 10 times the nonrecursive term's size.
3141 rel->tuples = 10 * cteplan->plan_rows;
3145 /* Otherwise just believe the CTE plan's output estimate */
3146 rel->tuples = cteplan->plan_rows;
3149 /* Now estimate number of output rows, etc */
3150 set_baserel_size_estimates(root, rel);
3156 * Set the estimated output width of a base relation.
3158 * NB: this works best on plain relations because it prefers to look at
3159 * real Vars. It will fail to make use of pg_statistic info when applied
3160 * to a subquery relation, even if the subquery outputs are simple vars
3161 * that we could have gotten info for. Is it worth trying to be smarter
3164 * The per-attribute width estimates are cached for possible re-use while
3165 * building join relations.
3168 set_rel_width(PlannerInfo *root, RelOptInfo *rel)
3170 Oid reloid = planner_rt_fetch(rel->relid, root)->relid;
3171 int32 tuple_width = 0;
3174 foreach(lc, rel->reltargetlist)
3176 Node *node = (Node *) lfirst(lc);
3180 Var *var = (Var *) node;
3184 Assert(var->varno == rel->relid);
3185 Assert(var->varattno >= rel->min_attr);
3186 Assert(var->varattno <= rel->max_attr);
3188 ndx = var->varattno - rel->min_attr;
3191 * The width probably hasn't been cached yet, but may as well
3194 if (rel->attr_widths[ndx] > 0)
3196 tuple_width += rel->attr_widths[ndx];
3200 /* Try to get column width from statistics */
3201 if (reloid != InvalidOid)
3203 item_width = get_attavgwidth(reloid, var->varattno);
3206 rel->attr_widths[ndx] = item_width;
3207 tuple_width += item_width;
3213 * Not a plain relation, or can't find statistics for it. Estimate
3214 * using just the type info.
3216 item_width = get_typavgwidth(var->vartype, var->vartypmod);
3217 Assert(item_width > 0);
3218 rel->attr_widths[ndx] = item_width;
3219 tuple_width += item_width;
3221 else if (IsA(node, PlaceHolderVar))
3223 PlaceHolderVar *phv = (PlaceHolderVar *) node;
3224 PlaceHolderInfo *phinfo = find_placeholder_info(root, phv);
3226 tuple_width += phinfo->ph_width;
3231 * We could be looking at an expression pulled up from a subquery,
3232 * or a ROW() representing a whole-row child Var, etc. Do what we
3233 * can using the expression type information.
3237 item_width = get_typavgwidth(exprType(node), exprTypmod(node));
3238 Assert(item_width > 0);
3239 tuple_width += item_width;
3242 Assert(tuple_width >= 0);
3243 rel->width = tuple_width;
3247 * relation_byte_size
3248 * Estimate the storage space in bytes for a given number of tuples
3249 * of a given width (size in bytes).
3252 relation_byte_size(double tuples, int width)
3254 return tuples * (MAXALIGN(width) + MAXALIGN(sizeof(HeapTupleHeaderData)));
3259 * Returns an estimate of the number of pages covered by a given
3260 * number of tuples of a given width (size in bytes).
3263 page_size(double tuples, int width)
3265 return ceil(relation_byte_size(tuples, width) / BLCKSZ);