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 * We compute two separate costs for each path:
31 * total_cost: total estimated cost to fetch all tuples
32 * startup_cost: cost that is expended before first tuple is fetched
33 * In some scenarios, such as when there is a LIMIT or we are implementing
34 * an EXISTS(...) sub-select, it is not necessary to fetch all tuples of the
35 * path's result. A caller can estimate the cost of fetching a partial
36 * result by interpolating between startup_cost and total_cost. In detail:
37 * actual_cost = startup_cost +
38 * (total_cost - startup_cost) * tuples_to_fetch / path->parent->rows;
39 * Note that a base relation's rows count (and, by extension, plan_rows for
40 * plan nodes below the LIMIT node) are set without regard to any LIMIT, so
41 * that this equation works properly. (Also, these routines guarantee not to
42 * set the rows count to zero, so there will be no zero divide.) The LIMIT is
43 * applied as a top-level plan node.
45 * For largely historical reasons, most of the routines in this module use
46 * the passed result Path only to store their startup_cost and total_cost
47 * results into. All the input data they need is passed as separate
48 * parameters, even though much of it could be extracted from the Path.
49 * An exception is made for the cost_XXXjoin() routines, which expect all
50 * the non-cost fields of the passed XXXPath to be filled in.
53 * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
54 * Portions Copyright (c) 1994, Regents of the University of California
57 * $PostgreSQL: pgsql/src/backend/optimizer/path/costsize.c,v 1.169 2006/11/11 01:14:19 tgl Exp $
59 *-------------------------------------------------------------------------
66 #include "executor/nodeHash.h"
67 #include "miscadmin.h"
68 #include "optimizer/clauses.h"
69 #include "optimizer/cost.h"
70 #include "optimizer/pathnode.h"
71 #include "parser/parsetree.h"
72 #include "utils/lsyscache.h"
73 #include "utils/selfuncs.h"
74 #include "utils/tuplesort.h"
77 #define LOG2(x) (log(x) / 0.693147180559945)
80 * Some Paths return less than the nominal number of rows of their parent
81 * relations; join nodes need to do this to get the correct input count:
83 #define PATH_ROWS(path) \
84 (IsA(path, UniquePath) ? \
85 ((UniquePath *) (path))->rows : \
89 double seq_page_cost = DEFAULT_SEQ_PAGE_COST;
90 double random_page_cost = DEFAULT_RANDOM_PAGE_COST;
91 double cpu_tuple_cost = DEFAULT_CPU_TUPLE_COST;
92 double cpu_index_tuple_cost = DEFAULT_CPU_INDEX_TUPLE_COST;
93 double cpu_operator_cost = DEFAULT_CPU_OPERATOR_COST;
95 int effective_cache_size = DEFAULT_EFFECTIVE_CACHE_SIZE;
97 Cost disable_cost = 100000000.0;
99 bool enable_seqscan = true;
100 bool enable_indexscan = true;
101 bool enable_bitmapscan = true;
102 bool enable_tidscan = true;
103 bool enable_sort = true;
104 bool enable_hashagg = true;
105 bool enable_nestloop = true;
106 bool enable_mergejoin = true;
107 bool enable_hashjoin = true;
110 static bool cost_qual_eval_walker(Node *node, QualCost *total);
111 static Selectivity approx_selectivity(PlannerInfo *root, List *quals,
113 static Selectivity join_in_selectivity(JoinPath *path, PlannerInfo *root);
114 static void set_rel_width(PlannerInfo *root, RelOptInfo *rel);
115 static double relation_byte_size(double tuples, int width);
116 static double page_size(double tuples, int width);
121 * Force a row-count estimate to a sane value.
124 clamp_row_est(double nrows)
127 * Force estimate to be at least one row, to make explain output look
128 * better and to avoid possible divide-by-zero when interpolating costs.
129 * Make it an integer, too.
142 * Determines and returns the cost of scanning a relation sequentially.
145 cost_seqscan(Path *path, PlannerInfo *root,
148 Cost startup_cost = 0;
152 /* Should only be applied to base relations */
153 Assert(baserel->relid > 0);
154 Assert(baserel->rtekind == RTE_RELATION);
157 startup_cost += disable_cost;
162 run_cost += seq_page_cost * baserel->pages;
165 startup_cost += baserel->baserestrictcost.startup;
166 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
167 run_cost += cpu_per_tuple * baserel->tuples;
169 path->startup_cost = startup_cost;
170 path->total_cost = startup_cost + run_cost;
175 * Determines and returns the cost of scanning a relation using an index.
177 * 'index' is the index to be used
178 * 'indexQuals' is the list of applicable qual clauses (implicit AND semantics)
179 * 'outer_rel' is the outer relation when we are considering using the index
180 * scan as the inside of a nestloop join (hence, some of the indexQuals
181 * are join clauses, and we should expect repeated scans of the index);
182 * NULL for a plain index scan
184 * cost_index() takes an IndexPath not just a Path, because it sets a few
185 * additional fields of the IndexPath besides startup_cost and total_cost.
186 * These fields are needed if the IndexPath is used in a BitmapIndexScan.
188 * NOTE: 'indexQuals' must contain only clauses usable as index restrictions.
189 * Any additional quals evaluated as qpquals may reduce the number of returned
190 * tuples, but they won't reduce the number of tuples we have to fetch from
191 * the table, so they don't reduce the scan cost.
193 * NOTE: as of 8.0, indexQuals is a list of RestrictInfo nodes, where formerly
194 * it was a list of bare clause expressions.
197 cost_index(IndexPath *path, PlannerInfo *root,
200 RelOptInfo *outer_rel)
202 RelOptInfo *baserel = index->rel;
203 Cost startup_cost = 0;
205 Cost indexStartupCost;
207 Selectivity indexSelectivity;
208 double indexCorrelation,
213 double tuples_fetched;
214 double pages_fetched;
216 /* Should only be applied to base relations */
217 Assert(IsA(baserel, RelOptInfo) &&
218 IsA(index, IndexOptInfo));
219 Assert(baserel->relid > 0);
220 Assert(baserel->rtekind == RTE_RELATION);
222 if (!enable_indexscan)
223 startup_cost += disable_cost;
226 * Call index-access-method-specific code to estimate the processing cost
227 * for scanning the index, as well as the selectivity of the index (ie,
228 * the fraction of main-table tuples we will have to retrieve) and its
229 * correlation to the main-table tuple order.
231 OidFunctionCall8(index->amcostestimate,
232 PointerGetDatum(root),
233 PointerGetDatum(index),
234 PointerGetDatum(indexQuals),
235 PointerGetDatum(outer_rel),
236 PointerGetDatum(&indexStartupCost),
237 PointerGetDatum(&indexTotalCost),
238 PointerGetDatum(&indexSelectivity),
239 PointerGetDatum(&indexCorrelation));
242 * Save amcostestimate's results for possible use in bitmap scan planning.
243 * We don't bother to save indexStartupCost or indexCorrelation, because a
244 * bitmap scan doesn't care about either.
246 path->indextotalcost = indexTotalCost;
247 path->indexselectivity = indexSelectivity;
249 /* all costs for touching index itself included here */
250 startup_cost += indexStartupCost;
251 run_cost += indexTotalCost - indexStartupCost;
253 /* estimate number of main-table tuples fetched */
254 tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
257 * Estimate number of main-table pages fetched, and compute I/O cost.
259 * When the index ordering is uncorrelated with the table ordering,
260 * we use an approximation proposed by Mackert and Lohman (see
261 * index_pages_fetched() for details) to compute the number of pages
262 * fetched, and then charge random_page_cost per page fetched.
264 * When the index ordering is exactly correlated with the table ordering
265 * (just after a CLUSTER, for example), the number of pages fetched should
266 * be exactly selectivity * table_size. What's more, all but the first
267 * will be sequential fetches, not the random fetches that occur in the
268 * uncorrelated case. So if the number of pages is more than 1, we
270 * random_page_cost + (pages_fetched - 1) * seq_page_cost
271 * For partially-correlated indexes, we ought to charge somewhere between
272 * these two estimates. We currently interpolate linearly between the
273 * estimates based on the correlation squared (XXX is that appropriate?).
276 if (outer_rel != NULL && outer_rel->rows > 1)
279 * For repeated indexscans, scale up the number of tuples fetched in
280 * the Mackert and Lohman formula by the number of scans, so that we
281 * estimate the number of pages fetched by all the scans. Then
282 * pro-rate the costs for one scan. In this case we assume all the
283 * fetches are random accesses. XXX it'd be good to include
284 * correlation in this model, but it's not clear how to do that
285 * without double-counting cache effects.
287 double num_scans = outer_rel->rows;
289 pages_fetched = index_pages_fetched(tuples_fetched * num_scans,
291 (double) index->pages,
294 run_cost += (pages_fetched * random_page_cost) / num_scans;
299 * Normal case: apply the Mackert and Lohman formula, and then
300 * interpolate between that and the correlation-derived result.
302 pages_fetched = index_pages_fetched(tuples_fetched,
304 (double) index->pages,
307 /* max_IO_cost is for the perfectly uncorrelated case (csquared=0) */
308 max_IO_cost = pages_fetched * random_page_cost;
310 /* min_IO_cost is for the perfectly correlated case (csquared=1) */
311 pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
312 min_IO_cost = random_page_cost;
313 if (pages_fetched > 1)
314 min_IO_cost += (pages_fetched - 1) * seq_page_cost;
317 * Now interpolate based on estimated index order correlation to get
318 * total disk I/O cost for main table accesses.
320 csquared = indexCorrelation * indexCorrelation;
322 run_cost += max_IO_cost + csquared * (min_IO_cost - max_IO_cost);
326 * Estimate CPU costs per tuple.
328 * Normally the indexquals will be removed from the list of restriction
329 * clauses that we have to evaluate as qpquals, so we should subtract
330 * their costs from baserestrictcost. But if we are doing a join then
331 * some of the indexquals are join clauses and shouldn't be subtracted.
332 * Rather than work out exactly how much to subtract, we don't subtract
335 startup_cost += baserel->baserestrictcost.startup;
336 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
338 if (outer_rel == NULL)
340 QualCost index_qual_cost;
342 cost_qual_eval(&index_qual_cost, indexQuals);
343 /* any startup cost still has to be paid ... */
344 cpu_per_tuple -= index_qual_cost.per_tuple;
347 run_cost += cpu_per_tuple * tuples_fetched;
349 path->path.startup_cost = startup_cost;
350 path->path.total_cost = startup_cost + run_cost;
354 * index_pages_fetched
355 * Estimate the number of pages actually fetched after accounting for
358 * We use an approximation proposed by Mackert and Lohman, "Index Scans
359 * Using a Finite LRU Buffer: A Validated I/O Model", ACM Transactions
360 * on Database Systems, Vol. 14, No. 3, September 1989, Pages 401-424.
361 * The Mackert and Lohman approximation is that the number of pages
364 * min(2TNs/(2T+Ns), T) when T <= b
365 * 2TNs/(2T+Ns) when T > b and Ns <= 2Tb/(2T-b)
366 * b + (Ns - 2Tb/(2T-b))*(T-b)/T when T > b and Ns > 2Tb/(2T-b)
368 * T = # pages in table
369 * N = # tuples in table
370 * s = selectivity = fraction of table to be scanned
371 * b = # buffer pages available (we include kernel space here)
373 * We assume that effective_cache_size is the total number of buffer pages
374 * available for the whole query, and pro-rate that space across all the
375 * tables in the query and the index currently under consideration. (This
376 * ignores space needed for other indexes used by the query, but since we
377 * don't know which indexes will get used, we can't estimate that very well;
378 * and in any case counting all the tables may well be an overestimate, since
379 * depending on the join plan not all the tables may be scanned concurrently.)
381 * The product Ns is the number of tuples fetched; we pass in that
382 * product rather than calculating it here. "pages" is the number of pages
383 * in the object under consideration (either an index or a table).
384 * "index_pages" is the amount to add to the total table space, which was
385 * computed for us by query_planner.
387 * Caller is expected to have ensured that tuples_fetched is greater than zero
388 * and rounded to integer (see clamp_row_est). The result will likewise be
389 * greater than zero and integral.
392 index_pages_fetched(double tuples_fetched, BlockNumber pages,
393 double index_pages, PlannerInfo *root)
395 double pages_fetched;
400 /* T is # pages in table, but don't allow it to be zero */
401 T = (pages > 1) ? (double) pages : 1.0;
403 /* Compute number of pages assumed to be competing for cache space */
404 total_pages = root->total_table_pages + index_pages;
405 total_pages = Max(total_pages, 1.0);
406 Assert(T <= total_pages);
408 /* b is pro-rated share of effective_cache_size */
409 b = (double) effective_cache_size *T / total_pages;
411 /* force it positive and integral */
417 /* This part is the Mackert and Lohman formula */
421 (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
422 if (pages_fetched >= T)
425 pages_fetched = ceil(pages_fetched);
431 lim = (2.0 * T * b) / (2.0 * T - b);
432 if (tuples_fetched <= lim)
435 (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
440 b + (tuples_fetched - lim) * (T - b) / T;
442 pages_fetched = ceil(pages_fetched);
444 return pages_fetched;
448 * get_indexpath_pages
449 * Determine the total size of the indexes used in a bitmap index path.
451 * Note: if the same index is used more than once in a bitmap tree, we will
452 * count it multiple times, which perhaps is the wrong thing ... but it's
453 * not completely clear, and detecting duplicates is difficult, so ignore it
457 get_indexpath_pages(Path *bitmapqual)
462 if (IsA(bitmapqual, BitmapAndPath))
464 BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
466 foreach(l, apath->bitmapquals)
468 result += get_indexpath_pages((Path *) lfirst(l));
471 else if (IsA(bitmapqual, BitmapOrPath))
473 BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
475 foreach(l, opath->bitmapquals)
477 result += get_indexpath_pages((Path *) lfirst(l));
480 else if (IsA(bitmapqual, IndexPath))
482 IndexPath *ipath = (IndexPath *) bitmapqual;
484 result = (double) ipath->indexinfo->pages;
487 elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
493 * cost_bitmap_heap_scan
494 * Determines and returns the cost of scanning a relation using a bitmap
495 * index-then-heap plan.
497 * 'baserel' is the relation to be scanned
498 * 'bitmapqual' is a tree of IndexPaths, BitmapAndPaths, and BitmapOrPaths
499 * 'outer_rel' is the outer relation when we are considering using the bitmap
500 * scan as the inside of a nestloop join (hence, some of the indexQuals
501 * are join clauses, and we should expect repeated scans of the table);
502 * NULL for a plain bitmap scan
504 * Note: if this is a join inner path, the component IndexPaths in bitmapqual
505 * should have been costed accordingly.
508 cost_bitmap_heap_scan(Path *path, PlannerInfo *root, RelOptInfo *baserel,
509 Path *bitmapqual, RelOptInfo *outer_rel)
511 Cost startup_cost = 0;
514 Selectivity indexSelectivity;
517 double tuples_fetched;
518 double pages_fetched;
521 /* Should only be applied to base relations */
522 Assert(IsA(baserel, RelOptInfo));
523 Assert(baserel->relid > 0);
524 Assert(baserel->rtekind == RTE_RELATION);
526 if (!enable_bitmapscan)
527 startup_cost += disable_cost;
530 * Fetch total cost of obtaining the bitmap, as well as its total
533 cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
535 startup_cost += indexTotalCost;
538 * Estimate number of main-table pages fetched.
540 tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
542 T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
544 if (outer_rel != NULL && outer_rel->rows > 1)
547 * For repeated bitmap scans, scale up the number of tuples fetched in
548 * the Mackert and Lohman formula by the number of scans, so that we
549 * estimate the number of pages fetched by all the scans. Then
550 * pro-rate for one scan.
552 double num_scans = outer_rel->rows;
554 pages_fetched = index_pages_fetched(tuples_fetched * num_scans,
556 get_indexpath_pages(bitmapqual),
558 pages_fetched /= num_scans;
563 * For a single scan, the number of heap pages that need to be fetched
564 * is the same as the Mackert and Lohman formula for the case T <= b
565 * (ie, no re-reads needed).
567 pages_fetched = (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
569 if (pages_fetched >= T)
572 pages_fetched = ceil(pages_fetched);
575 * For small numbers of pages we should charge random_page_cost apiece,
576 * while if nearly all the table's pages are being read, it's more
577 * appropriate to charge seq_page_cost apiece. The effect is nonlinear,
578 * too. For lack of a better idea, interpolate like this to determine the
581 if (pages_fetched >= 2.0)
582 cost_per_page = random_page_cost -
583 (random_page_cost - seq_page_cost) * sqrt(pages_fetched / T);
585 cost_per_page = random_page_cost;
587 run_cost += pages_fetched * cost_per_page;
590 * Estimate CPU costs per tuple.
592 * Often the indexquals don't need to be rechecked at each tuple ... but
593 * not always, especially not if there are enough tuples involved that the
594 * bitmaps become lossy. For the moment, just assume they will be
597 startup_cost += baserel->baserestrictcost.startup;
598 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
600 run_cost += cpu_per_tuple * tuples_fetched;
602 path->startup_cost = startup_cost;
603 path->total_cost = startup_cost + run_cost;
607 * cost_bitmap_tree_node
608 * Extract cost and selectivity from a bitmap tree node (index/and/or)
611 cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
613 if (IsA(path, IndexPath))
615 *cost = ((IndexPath *) path)->indextotalcost;
616 *selec = ((IndexPath *) path)->indexselectivity;
618 else if (IsA(path, BitmapAndPath))
620 *cost = path->total_cost;
621 *selec = ((BitmapAndPath *) path)->bitmapselectivity;
623 else if (IsA(path, BitmapOrPath))
625 *cost = path->total_cost;
626 *selec = ((BitmapOrPath *) path)->bitmapselectivity;
630 elog(ERROR, "unrecognized node type: %d", nodeTag(path));
631 *cost = *selec = 0; /* keep compiler quiet */
636 * cost_bitmap_and_node
637 * Estimate the cost of a BitmapAnd node
639 * Note that this considers only the costs of index scanning and bitmap
640 * creation, not the eventual heap access. In that sense the object isn't
641 * truly a Path, but it has enough path-like properties (costs in particular)
642 * to warrant treating it as one.
645 cost_bitmap_and_node(BitmapAndPath *path, PlannerInfo *root)
652 * We estimate AND selectivity on the assumption that the inputs are
653 * independent. This is probably often wrong, but we don't have the info
656 * The runtime cost of the BitmapAnd itself is estimated at 100x
657 * cpu_operator_cost for each tbm_intersect needed. Probably too small,
658 * definitely too simplistic?
662 foreach(l, path->bitmapquals)
664 Path *subpath = (Path *) lfirst(l);
666 Selectivity subselec;
668 cost_bitmap_tree_node(subpath, &subCost, &subselec);
672 totalCost += subCost;
673 if (l != list_head(path->bitmapquals))
674 totalCost += 100.0 * cpu_operator_cost;
676 path->bitmapselectivity = selec;
677 path->path.startup_cost = totalCost;
678 path->path.total_cost = totalCost;
682 * cost_bitmap_or_node
683 * Estimate the cost of a BitmapOr node
685 * See comments for cost_bitmap_and_node.
688 cost_bitmap_or_node(BitmapOrPath *path, PlannerInfo *root)
695 * We estimate OR selectivity on the assumption that the inputs are
696 * non-overlapping, since that's often the case in "x IN (list)" type
697 * situations. Of course, we clamp to 1.0 at the end.
699 * The runtime cost of the BitmapOr itself is estimated at 100x
700 * cpu_operator_cost for each tbm_union needed. Probably too small,
701 * definitely too simplistic? We are aware that the tbm_unions are
702 * optimized out when the inputs are BitmapIndexScans.
706 foreach(l, path->bitmapquals)
708 Path *subpath = (Path *) lfirst(l);
710 Selectivity subselec;
712 cost_bitmap_tree_node(subpath, &subCost, &subselec);
716 totalCost += subCost;
717 if (l != list_head(path->bitmapquals) &&
718 !IsA(subpath, IndexPath))
719 totalCost += 100.0 * cpu_operator_cost;
721 path->bitmapselectivity = Min(selec, 1.0);
722 path->path.startup_cost = totalCost;
723 path->path.total_cost = totalCost;
728 * Determines and returns the cost of scanning a relation using TIDs.
731 cost_tidscan(Path *path, PlannerInfo *root,
732 RelOptInfo *baserel, List *tidquals)
734 Cost startup_cost = 0;
740 /* Should only be applied to base relations */
741 Assert(baserel->relid > 0);
742 Assert(baserel->rtekind == RTE_RELATION);
745 startup_cost += disable_cost;
747 /* Count how many tuples we expect to retrieve */
751 if (IsA(lfirst(l), ScalarArrayOpExpr))
753 /* Each element of the array yields 1 tuple */
754 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) lfirst(l);
755 Node *arraynode = (Node *) lsecond(saop->args);
757 ntuples += estimate_array_length(arraynode);
761 /* It's just CTID = something, count 1 tuple */
766 /* disk costs --- assume each tuple on a different page */
767 run_cost += random_page_cost * ntuples;
770 startup_cost += baserel->baserestrictcost.startup;
771 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
772 run_cost += cpu_per_tuple * ntuples;
774 path->startup_cost = startup_cost;
775 path->total_cost = startup_cost + run_cost;
780 * Determines and returns the cost of scanning a subquery RTE.
783 cost_subqueryscan(Path *path, RelOptInfo *baserel)
789 /* Should only be applied to base relations that are subqueries */
790 Assert(baserel->relid > 0);
791 Assert(baserel->rtekind == RTE_SUBQUERY);
794 * Cost of path is cost of evaluating the subplan, plus cost of evaluating
795 * any restriction clauses that will be attached to the SubqueryScan node,
796 * plus cpu_tuple_cost to account for selection and projection overhead.
798 path->startup_cost = baserel->subplan->startup_cost;
799 path->total_cost = baserel->subplan->total_cost;
801 startup_cost = baserel->baserestrictcost.startup;
802 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
803 run_cost = cpu_per_tuple * baserel->tuples;
805 path->startup_cost += startup_cost;
806 path->total_cost += startup_cost + run_cost;
811 * Determines and returns the cost of scanning a function RTE.
814 cost_functionscan(Path *path, PlannerInfo *root, RelOptInfo *baserel)
816 Cost startup_cost = 0;
820 /* Should only be applied to base relations that are functions */
821 Assert(baserel->relid > 0);
822 Assert(baserel->rtekind == RTE_FUNCTION);
825 * For now, estimate function's cost at one operator eval per function
826 * call. Someday we should revive the function cost estimate columns in
829 cpu_per_tuple = cpu_operator_cost;
831 /* Add scanning CPU costs */
832 startup_cost += baserel->baserestrictcost.startup;
833 cpu_per_tuple += cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
834 run_cost += cpu_per_tuple * baserel->tuples;
836 path->startup_cost = startup_cost;
837 path->total_cost = startup_cost + run_cost;
842 * Determines and returns the cost of scanning a VALUES RTE.
845 cost_valuesscan(Path *path, PlannerInfo *root, RelOptInfo *baserel)
847 Cost startup_cost = 0;
851 /* Should only be applied to base relations that are values lists */
852 Assert(baserel->relid > 0);
853 Assert(baserel->rtekind == RTE_VALUES);
856 * For now, estimate list evaluation cost at one operator eval per list
857 * (probably pretty bogus, but is it worth being smarter?)
859 cpu_per_tuple = cpu_operator_cost;
861 /* Add scanning CPU costs */
862 startup_cost += baserel->baserestrictcost.startup;
863 cpu_per_tuple += cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
864 run_cost += cpu_per_tuple * baserel->tuples;
866 path->startup_cost = startup_cost;
867 path->total_cost = startup_cost + run_cost;
872 * Determines and returns the cost of sorting a relation, including
873 * the cost of reading the input data.
875 * If the total volume of data to sort is less than work_mem, we will do
876 * an in-memory sort, which requires no I/O and about t*log2(t) tuple
877 * comparisons for t tuples.
879 * If the total volume exceeds work_mem, we switch to a tape-style merge
880 * algorithm. There will still be about t*log2(t) tuple comparisons in
881 * total, but we will also need to write and read each tuple once per
882 * merge pass. We expect about ceil(logM(r)) merge passes where r is the
883 * number of initial runs formed and M is the merge order used by tuplesort.c.
884 * Since the average initial run should be about twice work_mem, we have
885 * disk traffic = 2 * relsize * ceil(logM(p / (2*work_mem)))
886 * cpu = comparison_cost * t * log2(t)
888 * The disk traffic is assumed to be 3/4ths sequential and 1/4th random
889 * accesses (XXX can't we refine that guess?)
891 * We charge two operator evals per tuple comparison, which should be in
892 * the right ballpark in most cases.
894 * 'pathkeys' is a list of sort keys
895 * 'input_cost' is the total cost for reading the input data
896 * 'tuples' is the number of tuples in the relation
897 * 'width' is the average tuple width in bytes
899 * NOTE: some callers currently pass NIL for pathkeys because they
900 * can't conveniently supply the sort keys. Since this routine doesn't
901 * currently do anything with pathkeys anyway, that doesn't matter...
902 * but if it ever does, it should react gracefully to lack of key data.
903 * (Actually, the thing we'd most likely be interested in is just the number
904 * of sort keys, which all callers *could* supply.)
907 cost_sort(Path *path, PlannerInfo *root,
908 List *pathkeys, Cost input_cost, double tuples, int width)
910 Cost startup_cost = input_cost;
912 double nbytes = relation_byte_size(tuples, width);
913 long work_mem_bytes = work_mem * 1024L;
916 startup_cost += disable_cost;
919 * We want to be sure the cost of a sort is never estimated as zero, even
920 * if passed-in tuple count is zero. Besides, mustn't do log(0)...
928 * Assume about two operator evals per tuple comparison and N log2 N
931 startup_cost += 2.0 * cpu_operator_cost * tuples * LOG2(tuples);
934 if (nbytes > work_mem_bytes)
936 double npages = ceil(nbytes / BLCKSZ);
937 double nruns = (nbytes / work_mem_bytes) * 0.5;
938 double mergeorder = tuplesort_merge_order(work_mem_bytes);
940 double npageaccesses;
942 /* Compute logM(r) as log(r) / log(M) */
943 if (nruns > mergeorder)
944 log_runs = ceil(log(nruns) / log(mergeorder));
947 npageaccesses = 2.0 * npages * log_runs;
948 /* Assume 3/4ths of accesses are sequential, 1/4th are not */
949 startup_cost += npageaccesses *
950 (seq_page_cost * 0.75 + random_page_cost * 0.25);
954 * Also charge a small amount (arbitrarily set equal to operator cost) per
957 run_cost += cpu_operator_cost * tuples;
959 path->startup_cost = startup_cost;
960 path->total_cost = startup_cost + run_cost;
965 * Determines and returns the cost of materializing a relation, including
966 * the cost of reading the input data.
968 * If the total volume of data to materialize exceeds work_mem, we will need
969 * to write it to disk, so the cost is much higher in that case.
972 cost_material(Path *path,
973 Cost input_cost, double tuples, int width)
975 Cost startup_cost = input_cost;
977 double nbytes = relation_byte_size(tuples, width);
978 long work_mem_bytes = work_mem * 1024L;
981 if (nbytes > work_mem_bytes)
983 double npages = ceil(nbytes / BLCKSZ);
985 /* We'll write during startup and read during retrieval */
986 startup_cost += seq_page_cost * npages;
987 run_cost += seq_page_cost * npages;
991 * Charge a very small amount per inserted tuple, to reflect bookkeeping
992 * costs. We use cpu_tuple_cost/10 for this. This is needed to break the
993 * tie that would otherwise exist between nestloop with A outer,
994 * materialized B inner and nestloop with B outer, materialized A inner.
995 * The extra cost ensures we'll prefer materializing the smaller rel.
997 startup_cost += cpu_tuple_cost * 0.1 * tuples;
1000 * Also charge a small amount per extracted tuple. We use cpu_tuple_cost
1001 * so that it doesn't appear worthwhile to materialize a bare seqscan.
1003 run_cost += cpu_tuple_cost * tuples;
1005 path->startup_cost = startup_cost;
1006 path->total_cost = startup_cost + run_cost;
1011 * Determines and returns the cost of performing an Agg plan node,
1012 * including the cost of its input.
1014 * Note: when aggstrategy == AGG_SORTED, caller must ensure that input costs
1015 * are for appropriately-sorted input.
1018 cost_agg(Path *path, PlannerInfo *root,
1019 AggStrategy aggstrategy, int numAggs,
1020 int numGroupCols, double numGroups,
1021 Cost input_startup_cost, Cost input_total_cost,
1022 double input_tuples)
1028 * We charge one cpu_operator_cost per aggregate function per input tuple,
1029 * and another one per output tuple (corresponding to transfn and finalfn
1030 * calls respectively). If we are grouping, we charge an additional
1031 * cpu_operator_cost per grouping column per input tuple for grouping
1034 * We will produce a single output tuple if not grouping, and a tuple per
1035 * group otherwise. We charge cpu_tuple_cost for each output tuple.
1037 * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the
1038 * same total CPU cost, but AGG_SORTED has lower startup cost. If the
1039 * input path is already sorted appropriately, AGG_SORTED should be
1040 * preferred (since it has no risk of memory overflow). This will happen
1041 * as long as the computed total costs are indeed exactly equal --- but if
1042 * there's roundoff error we might do the wrong thing. So be sure that
1043 * the computations below form the same intermediate values in the same
1046 if (aggstrategy == AGG_PLAIN)
1048 startup_cost = input_total_cost;
1049 startup_cost += cpu_operator_cost * (input_tuples + 1) * numAggs;
1050 /* we aren't grouping */
1051 total_cost = startup_cost + cpu_tuple_cost;
1053 else if (aggstrategy == AGG_SORTED)
1055 /* Here we are able to deliver output on-the-fly */
1056 startup_cost = input_startup_cost;
1057 total_cost = input_total_cost;
1058 /* calcs phrased this way to match HASHED case, see note above */
1059 total_cost += cpu_operator_cost * input_tuples * numGroupCols;
1060 total_cost += cpu_operator_cost * input_tuples * numAggs;
1061 total_cost += cpu_operator_cost * numGroups * numAggs;
1062 total_cost += cpu_tuple_cost * numGroups;
1066 /* must be AGG_HASHED */
1067 startup_cost = input_total_cost;
1068 startup_cost += cpu_operator_cost * input_tuples * numGroupCols;
1069 startup_cost += cpu_operator_cost * input_tuples * numAggs;
1070 total_cost = startup_cost;
1071 total_cost += cpu_operator_cost * numGroups * numAggs;
1072 total_cost += cpu_tuple_cost * numGroups;
1075 path->startup_cost = startup_cost;
1076 path->total_cost = total_cost;
1081 * Determines and returns the cost of performing a Group plan node,
1082 * including the cost of its input.
1084 * Note: caller must ensure that input costs are for appropriately-sorted
1088 cost_group(Path *path, PlannerInfo *root,
1089 int numGroupCols, double numGroups,
1090 Cost input_startup_cost, Cost input_total_cost,
1091 double input_tuples)
1096 startup_cost = input_startup_cost;
1097 total_cost = input_total_cost;
1100 * Charge one cpu_operator_cost per comparison per input tuple. We assume
1101 * all columns get compared at most of the tuples.
1103 total_cost += cpu_operator_cost * input_tuples * numGroupCols;
1105 path->startup_cost = startup_cost;
1106 path->total_cost = total_cost;
1110 * If a nestloop's inner path is an indexscan, be sure to use its estimated
1111 * output row count, which may be lower than the restriction-clause-only row
1112 * count of its parent. (We don't include this case in the PATH_ROWS macro
1113 * because it applies *only* to a nestloop's inner relation.) We have to
1114 * be prepared to recurse through Append nodes in case of an appendrel.
1117 nestloop_inner_path_rows(Path *path)
1121 if (IsA(path, IndexPath))
1122 result = ((IndexPath *) path)->rows;
1123 else if (IsA(path, BitmapHeapPath))
1124 result = ((BitmapHeapPath *) path)->rows;
1125 else if (IsA(path, AppendPath))
1130 foreach(l, ((AppendPath *) path)->subpaths)
1132 result += nestloop_inner_path_rows((Path *) lfirst(l));
1136 result = PATH_ROWS(path);
1143 * Determines and returns the cost of joining two relations using the
1144 * nested loop algorithm.
1146 * 'path' is already filled in except for the cost fields
1149 cost_nestloop(NestPath *path, PlannerInfo *root)
1151 Path *outer_path = path->outerjoinpath;
1152 Path *inner_path = path->innerjoinpath;
1153 Cost startup_cost = 0;
1156 QualCost restrict_qual_cost;
1157 double outer_path_rows = PATH_ROWS(outer_path);
1158 double inner_path_rows = nestloop_inner_path_rows(inner_path);
1160 Selectivity joininfactor;
1162 if (!enable_nestloop)
1163 startup_cost += disable_cost;
1166 * If we're doing JOIN_IN then we will stop scanning inner tuples for an
1167 * outer tuple as soon as we have one match. Account for the effects of
1168 * this by scaling down the cost estimates in proportion to the JOIN_IN
1169 * selectivity. (This assumes that all the quals attached to the join are
1170 * IN quals, which should be true.)
1172 joininfactor = join_in_selectivity(path, root);
1174 /* cost of source data */
1177 * NOTE: clearly, we must pay both outer and inner paths' startup_cost
1178 * before we can start returning tuples, so the join's startup cost is
1179 * their sum. What's not so clear is whether the inner path's
1180 * startup_cost must be paid again on each rescan of the inner path. This
1181 * is not true if the inner path is materialized or is a hashjoin, but
1182 * probably is true otherwise.
1184 startup_cost += outer_path->startup_cost + inner_path->startup_cost;
1185 run_cost += outer_path->total_cost - outer_path->startup_cost;
1186 if (IsA(inner_path, MaterialPath) ||
1187 IsA(inner_path, HashPath))
1189 /* charge only run cost for each iteration of inner path */
1194 * charge startup cost for each iteration of inner path, except we
1195 * already charged the first startup_cost in our own startup
1197 run_cost += (outer_path_rows - 1) * inner_path->startup_cost;
1199 run_cost += outer_path_rows *
1200 (inner_path->total_cost - inner_path->startup_cost) * joininfactor;
1203 * Compute number of tuples processed (not number emitted!)
1205 ntuples = outer_path_rows * inner_path_rows * joininfactor;
1208 cost_qual_eval(&restrict_qual_cost, path->joinrestrictinfo);
1209 startup_cost += restrict_qual_cost.startup;
1210 cpu_per_tuple = cpu_tuple_cost + restrict_qual_cost.per_tuple;
1211 run_cost += cpu_per_tuple * ntuples;
1213 path->path.startup_cost = startup_cost;
1214 path->path.total_cost = startup_cost + run_cost;
1219 * Determines and returns the cost of joining two relations using the
1220 * merge join algorithm.
1222 * 'path' is already filled in except for the cost fields
1224 * Notes: path's mergeclauses should be a subset of the joinrestrictinfo list;
1225 * outersortkeys and innersortkeys are lists of the keys to be used
1226 * to sort the outer and inner relations, or NIL if no explicit
1227 * sort is needed because the source path is already ordered.
1230 cost_mergejoin(MergePath *path, PlannerInfo *root)
1232 Path *outer_path = path->jpath.outerjoinpath;
1233 Path *inner_path = path->jpath.innerjoinpath;
1234 List *mergeclauses = path->path_mergeclauses;
1235 List *outersortkeys = path->outersortkeys;
1236 List *innersortkeys = path->innersortkeys;
1237 Cost startup_cost = 0;
1240 Selectivity merge_selec;
1241 QualCost merge_qual_cost;
1242 QualCost qp_qual_cost;
1243 RestrictInfo *firstclause;
1244 double outer_path_rows = PATH_ROWS(outer_path);
1245 double inner_path_rows = PATH_ROWS(inner_path);
1248 double mergejointuples,
1251 Selectivity outerscansel,
1253 Selectivity joininfactor;
1254 Path sort_path; /* dummy for result of cost_sort */
1256 if (!enable_mergejoin)
1257 startup_cost += disable_cost;
1260 * Compute cost and selectivity of the mergequals and qpquals (other
1261 * restriction clauses) separately. We use approx_selectivity here for
1262 * speed --- in most cases, any errors won't affect the result much.
1264 * Note: it's probably bogus to use the normal selectivity calculation
1265 * here when either the outer or inner path is a UniquePath.
1267 merge_selec = approx_selectivity(root, mergeclauses,
1268 path->jpath.jointype);
1269 cost_qual_eval(&merge_qual_cost, mergeclauses);
1270 cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo);
1271 qp_qual_cost.startup -= merge_qual_cost.startup;
1272 qp_qual_cost.per_tuple -= merge_qual_cost.per_tuple;
1274 /* approx # tuples passing the merge quals */
1275 mergejointuples = clamp_row_est(merge_selec * outer_path_rows * inner_path_rows);
1278 * When there are equal merge keys in the outer relation, the mergejoin
1279 * must rescan any matching tuples in the inner relation. This means
1280 * re-fetching inner tuples. Our cost model for this is that a re-fetch
1281 * costs the same as an original fetch, which is probably an overestimate;
1282 * but on the other hand we ignore the bookkeeping costs of mark/restore.
1283 * Not clear if it's worth developing a more refined model.
1285 * The number of re-fetches can be estimated approximately as size of
1286 * merge join output minus size of inner relation. Assume that the
1287 * distinct key values are 1, 2, ..., and denote the number of values of
1288 * each key in the outer relation as m1, m2, ...; in the inner relation,
1289 * n1, n2, ... Then we have
1291 * size of join = m1 * n1 + m2 * n2 + ...
1293 * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... = m1 *
1294 * n1 + m2 * n2 + ... - (n1 + n2 + ...) = size of join - size of inner
1297 * This equation works correctly for outer tuples having no inner match
1298 * (nk = 0), but not for inner tuples having no outer match (mk = 0); we
1299 * are effectively subtracting those from the number of rescanned tuples,
1300 * when we should not. Can we do better without expensive selectivity
1303 if (IsA(outer_path, UniquePath))
1304 rescannedtuples = 0;
1307 rescannedtuples = mergejointuples - inner_path_rows;
1308 /* Must clamp because of possible underestimate */
1309 if (rescannedtuples < 0)
1310 rescannedtuples = 0;
1312 /* We'll inflate inner run cost this much to account for rescanning */
1313 rescanratio = 1.0 + (rescannedtuples / inner_path_rows);
1316 * A merge join will stop as soon as it exhausts either input stream
1317 * (unless it's an outer join, in which case the outer side has to be
1318 * scanned all the way anyway). Estimate fraction of the left and right
1319 * inputs that will actually need to be scanned. We use only the first
1320 * (most significant) merge clause for this purpose.
1322 * Since this calculation is somewhat expensive, and will be the same for
1323 * all mergejoin paths associated with the merge clause, we cache the
1324 * results in the RestrictInfo node.
1326 if (mergeclauses && path->jpath.jointype != JOIN_FULL)
1328 firstclause = (RestrictInfo *) linitial(mergeclauses);
1329 if (firstclause->left_mergescansel < 0) /* not computed yet? */
1330 mergejoinscansel(root, (Node *) firstclause->clause,
1331 &firstclause->left_mergescansel,
1332 &firstclause->right_mergescansel);
1334 if (bms_is_subset(firstclause->left_relids, outer_path->parent->relids))
1336 /* left side of clause is outer */
1337 outerscansel = firstclause->left_mergescansel;
1338 innerscansel = firstclause->right_mergescansel;
1342 /* left side of clause is inner */
1343 outerscansel = firstclause->right_mergescansel;
1344 innerscansel = firstclause->left_mergescansel;
1346 if (path->jpath.jointype == JOIN_LEFT)
1348 else if (path->jpath.jointype == JOIN_RIGHT)
1353 /* cope with clauseless or full mergejoin */
1354 outerscansel = innerscansel = 1.0;
1357 /* convert selectivity to row count; must scan at least one row */
1358 outer_rows = clamp_row_est(outer_path_rows * outerscansel);
1359 inner_rows = clamp_row_est(inner_path_rows * innerscansel);
1362 * Readjust scan selectivities to account for above rounding. This is
1363 * normally an insignificant effect, but when there are only a few rows in
1364 * the inputs, failing to do this makes for a large percentage error.
1366 outerscansel = outer_rows / outer_path_rows;
1367 innerscansel = inner_rows / inner_path_rows;
1369 /* cost of source data */
1371 if (outersortkeys) /* do we need to sort outer? */
1373 cost_sort(&sort_path,
1376 outer_path->total_cost,
1378 outer_path->parent->width);
1379 startup_cost += sort_path.startup_cost;
1380 run_cost += (sort_path.total_cost - sort_path.startup_cost)
1385 startup_cost += outer_path->startup_cost;
1386 run_cost += (outer_path->total_cost - outer_path->startup_cost)
1390 if (innersortkeys) /* do we need to sort inner? */
1392 cost_sort(&sort_path,
1395 inner_path->total_cost,
1397 inner_path->parent->width);
1398 startup_cost += sort_path.startup_cost;
1399 run_cost += (sort_path.total_cost - sort_path.startup_cost)
1400 * innerscansel * rescanratio;
1404 startup_cost += inner_path->startup_cost;
1405 run_cost += (inner_path->total_cost - inner_path->startup_cost)
1406 * innerscansel * rescanratio;
1412 * If we're doing JOIN_IN then we will stop outputting inner tuples for an
1413 * outer tuple as soon as we have one match. Account for the effects of
1414 * this by scaling down the cost estimates in proportion to the expected
1415 * output size. (This assumes that all the quals attached to the join are
1416 * IN quals, which should be true.)
1418 joininfactor = join_in_selectivity(&path->jpath, root);
1421 * The number of tuple comparisons needed is approximately number of outer
1422 * rows plus number of inner rows plus number of rescanned tuples (can we
1423 * refine this?). At each one, we need to evaluate the mergejoin quals.
1424 * NOTE: JOIN_IN mode does not save any work here, so do NOT include
1427 startup_cost += merge_qual_cost.startup;
1428 run_cost += merge_qual_cost.per_tuple *
1429 (outer_rows + inner_rows * rescanratio);
1432 * For each tuple that gets through the mergejoin proper, we charge
1433 * cpu_tuple_cost plus the cost of evaluating additional restriction
1434 * clauses that are to be applied at the join. (This is pessimistic since
1435 * not all of the quals may get evaluated at each tuple.) This work is
1436 * skipped in JOIN_IN mode, so apply the factor.
1438 startup_cost += qp_qual_cost.startup;
1439 cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
1440 run_cost += cpu_per_tuple * mergejointuples * joininfactor;
1442 path->jpath.path.startup_cost = startup_cost;
1443 path->jpath.path.total_cost = startup_cost + run_cost;
1448 * Determines and returns the cost of joining two relations using the
1449 * hash join algorithm.
1451 * 'path' is already filled in except for the cost fields
1453 * Note: path's hashclauses should be a subset of the joinrestrictinfo list
1456 cost_hashjoin(HashPath *path, PlannerInfo *root)
1458 Path *outer_path = path->jpath.outerjoinpath;
1459 Path *inner_path = path->jpath.innerjoinpath;
1460 List *hashclauses = path->path_hashclauses;
1461 Cost startup_cost = 0;
1464 Selectivity hash_selec;
1465 QualCost hash_qual_cost;
1466 QualCost qp_qual_cost;
1467 double hashjointuples;
1468 double outer_path_rows = PATH_ROWS(outer_path);
1469 double inner_path_rows = PATH_ROWS(inner_path);
1470 double outerbytes = relation_byte_size(outer_path_rows,
1471 outer_path->parent->width);
1472 double innerbytes = relation_byte_size(inner_path_rows,
1473 inner_path->parent->width);
1474 int num_hashclauses = list_length(hashclauses);
1477 double virtualbuckets;
1478 Selectivity innerbucketsize;
1479 Selectivity joininfactor;
1482 if (!enable_hashjoin)
1483 startup_cost += disable_cost;
1486 * Compute cost and selectivity of the hashquals and qpquals (other
1487 * restriction clauses) separately. We use approx_selectivity here for
1488 * speed --- in most cases, any errors won't affect the result much.
1490 * Note: it's probably bogus to use the normal selectivity calculation
1491 * here when either the outer or inner path is a UniquePath.
1493 hash_selec = approx_selectivity(root, hashclauses,
1494 path->jpath.jointype);
1495 cost_qual_eval(&hash_qual_cost, hashclauses);
1496 cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo);
1497 qp_qual_cost.startup -= hash_qual_cost.startup;
1498 qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
1500 /* approx # tuples passing the hash quals */
1501 hashjointuples = clamp_row_est(hash_selec * outer_path_rows * inner_path_rows);
1503 /* cost of source data */
1504 startup_cost += outer_path->startup_cost;
1505 run_cost += outer_path->total_cost - outer_path->startup_cost;
1506 startup_cost += inner_path->total_cost;
1509 * Cost of computing hash function: must do it once per input tuple. We
1510 * charge one cpu_operator_cost for each column's hash function.
1512 * XXX when a hashclause is more complex than a single operator, we really
1513 * should charge the extra eval costs of the left or right side, as
1514 * appropriate, here. This seems more work than it's worth at the moment.
1516 startup_cost += cpu_operator_cost * num_hashclauses * inner_path_rows;
1517 run_cost += cpu_operator_cost * num_hashclauses * outer_path_rows;
1519 /* Get hash table size that executor would use for inner relation */
1520 ExecChooseHashTableSize(inner_path_rows,
1521 inner_path->parent->width,
1524 virtualbuckets = (double) numbuckets *(double) numbatches;
1527 * Determine bucketsize fraction for inner relation. We use the smallest
1528 * bucketsize estimated for any individual hashclause; this is undoubtedly
1531 * BUT: if inner relation has been unique-ified, we can assume it's good
1532 * for hashing. This is important both because it's the right answer, and
1533 * because we avoid contaminating the cache with a value that's wrong for
1534 * non-unique-ified paths.
1536 if (IsA(inner_path, UniquePath))
1537 innerbucketsize = 1.0 / virtualbuckets;
1540 innerbucketsize = 1.0;
1541 foreach(hcl, hashclauses)
1543 RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(hcl);
1544 Selectivity thisbucketsize;
1546 Assert(IsA(restrictinfo, RestrictInfo));
1549 * First we have to figure out which side of the hashjoin clause
1550 * is the inner side.
1552 * Since we tend to visit the same clauses over and over when
1553 * planning a large query, we cache the bucketsize estimate in the
1554 * RestrictInfo node to avoid repeated lookups of statistics.
1556 if (bms_is_subset(restrictinfo->right_relids,
1557 inner_path->parent->relids))
1559 /* righthand side is inner */
1560 thisbucketsize = restrictinfo->right_bucketsize;
1561 if (thisbucketsize < 0)
1563 /* not cached yet */
1565 estimate_hash_bucketsize(root,
1566 get_rightop(restrictinfo->clause),
1568 restrictinfo->right_bucketsize = thisbucketsize;
1573 Assert(bms_is_subset(restrictinfo->left_relids,
1574 inner_path->parent->relids));
1575 /* lefthand side is inner */
1576 thisbucketsize = restrictinfo->left_bucketsize;
1577 if (thisbucketsize < 0)
1579 /* not cached yet */
1581 estimate_hash_bucketsize(root,
1582 get_leftop(restrictinfo->clause),
1584 restrictinfo->left_bucketsize = thisbucketsize;
1588 if (innerbucketsize > thisbucketsize)
1589 innerbucketsize = thisbucketsize;
1594 * If inner relation is too big then we will need to "batch" the join,
1595 * which implies writing and reading most of the tuples to disk an extra
1596 * time. Charge one cost unit per page of I/O (correct since it should be
1597 * nice and sequential...). Writing the inner rel counts as startup cost,
1598 * all the rest as run cost.
1602 double outerpages = page_size(outer_path_rows,
1603 outer_path->parent->width);
1604 double innerpages = page_size(inner_path_rows,
1605 inner_path->parent->width);
1607 startup_cost += innerpages;
1608 run_cost += innerpages + 2 * outerpages;
1614 * If we're doing JOIN_IN then we will stop comparing inner tuples to an
1615 * outer tuple as soon as we have one match. Account for the effects of
1616 * this by scaling down the cost estimates in proportion to the expected
1617 * output size. (This assumes that all the quals attached to the join are
1618 * IN quals, which should be true.)
1620 joininfactor = join_in_selectivity(&path->jpath, root);
1623 * The number of tuple comparisons needed is the number of outer tuples
1624 * times the typical number of tuples in a hash bucket, which is the inner
1625 * relation size times its bucketsize fraction. At each one, we need to
1626 * evaluate the hashjoin quals. (Note: charging the full qual eval cost
1627 * at each tuple is pessimistic, since we don't evaluate the quals unless
1628 * the hash values match exactly.)
1630 startup_cost += hash_qual_cost.startup;
1631 run_cost += hash_qual_cost.per_tuple *
1632 outer_path_rows * clamp_row_est(inner_path_rows * innerbucketsize) *
1636 * For each tuple that gets through the hashjoin proper, we charge
1637 * cpu_tuple_cost plus the cost of evaluating additional restriction
1638 * clauses that are to be applied at the join. (This is pessimistic since
1639 * not all of the quals may get evaluated at each tuple.)
1641 startup_cost += qp_qual_cost.startup;
1642 cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
1643 run_cost += cpu_per_tuple * hashjointuples * joininfactor;
1646 * Bias against putting larger relation on inside. We don't want an
1647 * absolute prohibition, though, since larger relation might have better
1648 * bucketsize --- and we can't trust the size estimates unreservedly,
1649 * anyway. Instead, inflate the run cost by the square root of the size
1650 * ratio. (Why square root? No real good reason, but it seems
1653 * Note: before 7.4 we implemented this by inflating startup cost; but if
1654 * there's a disable_cost component in the input paths' startup cost, that
1655 * unfairly penalizes the hash. Probably it'd be better to keep track of
1656 * disable penalty separately from cost.
1658 if (innerbytes > outerbytes && outerbytes > 0)
1659 run_cost *= sqrt(innerbytes / outerbytes);
1661 path->jpath.path.startup_cost = startup_cost;
1662 path->jpath.path.total_cost = startup_cost + run_cost;
1668 * Estimate the CPU costs of evaluating a WHERE clause.
1669 * The input can be either an implicitly-ANDed list of boolean
1670 * expressions, or a list of RestrictInfo nodes.
1671 * The result includes both a one-time (startup) component,
1672 * and a per-evaluation component.
1675 cost_qual_eval(QualCost *cost, List *quals)
1680 cost->per_tuple = 0;
1682 /* We don't charge any cost for the implicit ANDing at top level ... */
1686 Node *qual = (Node *) lfirst(l);
1689 * RestrictInfo nodes contain an eval_cost field reserved for this
1690 * routine's use, so that it's not necessary to evaluate the qual
1691 * clause's cost more than once. If the clause's cost hasn't been
1692 * computed yet, the field's startup value will contain -1.
1694 * If the RestrictInfo is marked pseudoconstant, it will be tested
1695 * only once, so treat its cost as all startup cost.
1697 if (qual && IsA(qual, RestrictInfo))
1699 RestrictInfo *rinfo = (RestrictInfo *) qual;
1701 if (rinfo->eval_cost.startup < 0)
1703 rinfo->eval_cost.startup = 0;
1704 rinfo->eval_cost.per_tuple = 0;
1705 cost_qual_eval_walker((Node *) rinfo->clause,
1707 if (rinfo->pseudoconstant)
1709 /* count one execution during startup */
1710 rinfo->eval_cost.startup += rinfo->eval_cost.per_tuple;
1711 rinfo->eval_cost.per_tuple = 0;
1714 cost->startup += rinfo->eval_cost.startup;
1715 cost->per_tuple += rinfo->eval_cost.per_tuple;
1719 /* If it's a bare expression, must always do it the hard way */
1720 cost_qual_eval_walker(qual, cost);
1726 cost_qual_eval_walker(Node *node, QualCost *total)
1732 * Our basic strategy is to charge one cpu_operator_cost for each operator
1733 * or function node in the given tree. Vars and Consts are charged zero,
1734 * and so are boolean operators (AND, OR, NOT). Simplistic, but a lot
1735 * better than no model at all.
1737 * Should we try to account for the possibility of short-circuit
1738 * evaluation of AND/OR?
1740 if (IsA(node, FuncExpr) ||
1741 IsA(node, OpExpr) ||
1742 IsA(node, DistinctExpr) ||
1743 IsA(node, NullIfExpr))
1744 total->per_tuple += cpu_operator_cost;
1745 else if (IsA(node, ScalarArrayOpExpr))
1748 * Estimate that the operator will be applied to about half of the
1749 * array elements before the answer is determined.
1751 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
1752 Node *arraynode = (Node *) lsecond(saop->args);
1755 cpu_operator_cost * estimate_array_length(arraynode) * 0.5;
1757 else if (IsA(node, RowCompareExpr))
1759 /* Conservatively assume we will check all the columns */
1760 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
1762 total->per_tuple += cpu_operator_cost * list_length(rcexpr->opnos);
1764 else if (IsA(node, SubLink))
1766 /* This routine should not be applied to un-planned expressions */
1767 elog(ERROR, "cannot handle unplanned sub-select");
1769 else if (IsA(node, SubPlan))
1772 * A subplan node in an expression typically indicates that the
1773 * subplan will be executed on each evaluation, so charge accordingly.
1774 * (Sub-selects that can be executed as InitPlans have already been
1775 * removed from the expression.)
1777 * An exception occurs when we have decided we can implement the
1778 * subplan by hashing.
1780 SubPlan *subplan = (SubPlan *) node;
1781 Plan *plan = subplan->plan;
1783 if (subplan->useHashTable)
1786 * If we are using a hash table for the subquery outputs, then the
1787 * cost of evaluating the query is a one-time cost. We charge one
1788 * cpu_operator_cost per tuple for the work of loading the
1791 total->startup += plan->total_cost +
1792 cpu_operator_cost * plan->plan_rows;
1795 * The per-tuple costs include the cost of evaluating the lefthand
1796 * expressions, plus the cost of probing the hashtable. Recursion
1797 * into the testexpr will handle the lefthand expressions
1798 * properly, and will count one cpu_operator_cost for each
1799 * comparison operator. That is probably too low for the probing
1800 * cost, but it's hard to make a better estimate, so live with it
1807 * Otherwise we will be rescanning the subplan output on each
1808 * evaluation. We need to estimate how much of the output we will
1809 * actually need to scan. NOTE: this logic should agree with the
1810 * estimates used by make_subplan() in plan/subselect.c.
1812 Cost plan_run_cost = plan->total_cost - plan->startup_cost;
1814 if (subplan->subLinkType == EXISTS_SUBLINK)
1816 /* we only need to fetch 1 tuple */
1817 total->per_tuple += plan_run_cost / plan->plan_rows;
1819 else if (subplan->subLinkType == ALL_SUBLINK ||
1820 subplan->subLinkType == ANY_SUBLINK)
1822 /* assume we need 50% of the tuples */
1823 total->per_tuple += 0.50 * plan_run_cost;
1824 /* also charge a cpu_operator_cost per row examined */
1825 total->per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
1829 /* assume we need all tuples */
1830 total->per_tuple += plan_run_cost;
1834 * Also account for subplan's startup cost. If the subplan is
1835 * uncorrelated or undirect correlated, AND its topmost node is a
1836 * Sort or Material node, assume that we'll only need to pay its
1837 * startup cost once; otherwise assume we pay the startup cost
1840 if (subplan->parParam == NIL &&
1842 IsA(plan, Material)))
1843 total->startup += plan->startup_cost;
1845 total->per_tuple += plan->startup_cost;
1849 return expression_tree_walker(node, cost_qual_eval_walker,
1855 * approx_selectivity
1856 * Quick-and-dirty estimation of clause selectivities.
1857 * The input can be either an implicitly-ANDed list of boolean
1858 * expressions, or a list of RestrictInfo nodes (typically the latter).
1860 * This is quick-and-dirty because we bypass clauselist_selectivity, and
1861 * simply multiply the independent clause selectivities together. Now
1862 * clauselist_selectivity often can't do any better than that anyhow, but
1863 * for some situations (such as range constraints) it is smarter. However,
1864 * we can't effectively cache the results of clauselist_selectivity, whereas
1865 * the individual clause selectivities can be and are cached.
1867 * Since we are only using the results to estimate how many potential
1868 * output tuples are generated and passed through qpqual checking, it
1869 * seems OK to live with the approximation.
1872 approx_selectivity(PlannerInfo *root, List *quals, JoinType jointype)
1874 Selectivity total = 1.0;
1879 Node *qual = (Node *) lfirst(l);
1881 /* Note that clause_selectivity will be able to cache its result */
1882 total *= clause_selectivity(root, qual, 0, jointype);
1889 * set_baserel_size_estimates
1890 * Set the size estimates for the given base relation.
1892 * The rel's targetlist and restrictinfo list must have been constructed
1895 * We set the following fields of the rel node:
1896 * rows: the estimated number of output tuples (after applying
1897 * restriction clauses).
1898 * width: the estimated average output tuple width in bytes.
1899 * baserestrictcost: estimated cost of evaluating baserestrictinfo clauses.
1902 set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
1906 /* Should only be applied to base relations */
1907 Assert(rel->relid > 0);
1909 nrows = rel->tuples *
1910 clauselist_selectivity(root,
1911 rel->baserestrictinfo,
1915 rel->rows = clamp_row_est(nrows);
1917 cost_qual_eval(&rel->baserestrictcost, rel->baserestrictinfo);
1919 set_rel_width(root, rel);
1923 * set_joinrel_size_estimates
1924 * Set the size estimates for the given join relation.
1926 * The rel's targetlist must have been constructed already, and a
1927 * restriction clause list that matches the given component rels must
1930 * Since there is more than one way to make a joinrel for more than two
1931 * base relations, the results we get here could depend on which component
1932 * rel pair is provided. In theory we should get the same answers no matter
1933 * which pair is provided; in practice, since the selectivity estimation
1934 * routines don't handle all cases equally well, we might not. But there's
1935 * not much to be done about it. (Would it make sense to repeat the
1936 * calculations for each pair of input rels that's encountered, and somehow
1937 * average the results? Probably way more trouble than it's worth.)
1939 * It's important that the results for symmetric JoinTypes be symmetric,
1940 * eg, (rel1, rel2, JOIN_LEFT) should produce the same result as (rel2,
1941 * rel1, JOIN_RIGHT). Also, JOIN_IN should produce the same result as
1942 * JOIN_UNIQUE_INNER, likewise JOIN_REVERSE_IN == JOIN_UNIQUE_OUTER.
1944 * We set only the rows field here. The width field was already set by
1945 * build_joinrel_tlist, and baserestrictcost is not used for join rels.
1948 set_joinrel_size_estimates(PlannerInfo *root, RelOptInfo *rel,
1949 RelOptInfo *outer_rel,
1950 RelOptInfo *inner_rel,
1960 * Compute joinclause selectivity. Note that we are only considering
1961 * clauses that become restriction clauses at this join level; we are not
1962 * double-counting them because they were not considered in estimating the
1963 * sizes of the component rels.
1965 * For an outer join, we have to distinguish the selectivity of the
1966 * join's own clauses (JOIN/ON conditions) from any clauses that were
1967 * "pushed down". For inner joins we just count them all as joinclauses.
1969 if (IS_OUTER_JOIN(jointype))
1971 List *joinquals = NIL;
1972 List *pushedquals = NIL;
1975 /* Grovel through the clauses to separate into two lists */
1976 foreach(l, restrictlist)
1978 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
1980 Assert(IsA(rinfo, RestrictInfo));
1981 if (rinfo->is_pushed_down)
1982 pushedquals = lappend(pushedquals, rinfo);
1984 joinquals = lappend(joinquals, rinfo);
1987 /* Get the separate selectivities */
1988 jselec = clauselist_selectivity(root,
1992 pselec = clauselist_selectivity(root,
1997 /* Avoid leaking a lot of ListCells */
1998 list_free(joinquals);
1999 list_free(pushedquals);
2003 jselec = clauselist_selectivity(root,
2007 pselec = 0.0; /* not used, keep compiler quiet */
2011 * Basically, we multiply size of Cartesian product by selectivity.
2013 * If we are doing an outer join, take that into account: the joinqual
2014 * selectivity has to be clamped using the knowledge that the output must
2015 * be at least as large as the non-nullable input. However, any
2016 * pushed-down quals are applied after the outer join, so their
2017 * selectivity applies fully.
2019 * For JOIN_IN and variants, the Cartesian product is figured with respect
2020 * to a unique-ified input, and then we can clamp to the size of the other
2026 nrows = outer_rel->rows * inner_rel->rows * jselec;
2029 nrows = outer_rel->rows * inner_rel->rows * jselec;
2030 if (nrows < outer_rel->rows)
2031 nrows = outer_rel->rows;
2035 nrows = outer_rel->rows * inner_rel->rows * jselec;
2036 if (nrows < inner_rel->rows)
2037 nrows = inner_rel->rows;
2041 nrows = outer_rel->rows * inner_rel->rows * jselec;
2042 if (nrows < outer_rel->rows)
2043 nrows = outer_rel->rows;
2044 if (nrows < inner_rel->rows)
2045 nrows = inner_rel->rows;
2049 case JOIN_UNIQUE_INNER:
2050 upath = create_unique_path(root, inner_rel,
2051 inner_rel->cheapest_total_path);
2052 nrows = outer_rel->rows * upath->rows * jselec;
2053 if (nrows > outer_rel->rows)
2054 nrows = outer_rel->rows;
2056 case JOIN_REVERSE_IN:
2057 case JOIN_UNIQUE_OUTER:
2058 upath = create_unique_path(root, outer_rel,
2059 outer_rel->cheapest_total_path);
2060 nrows = upath->rows * inner_rel->rows * jselec;
2061 if (nrows > inner_rel->rows)
2062 nrows = inner_rel->rows;
2065 elog(ERROR, "unrecognized join type: %d", (int) jointype);
2066 nrows = 0; /* keep compiler quiet */
2070 rel->rows = clamp_row_est(nrows);
2074 * join_in_selectivity
2075 * Determines the factor by which a JOIN_IN join's result is expected
2076 * to be smaller than an ordinary inner join.
2078 * 'path' is already filled in except for the cost fields
2081 join_in_selectivity(JoinPath *path, PlannerInfo *root)
2083 RelOptInfo *innerrel;
2084 UniquePath *innerunique;
2088 /* Return 1.0 whenever it's not JOIN_IN */
2089 if (path->jointype != JOIN_IN)
2093 * Return 1.0 if the inner side is already known unique. The case where
2094 * the inner path is already a UniquePath probably cannot happen in
2095 * current usage, but check it anyway for completeness. The interesting
2096 * case is where we've determined the inner relation itself is unique,
2097 * which we can check by looking at the rows estimate for its UniquePath.
2099 if (IsA(path->innerjoinpath, UniquePath))
2101 innerrel = path->innerjoinpath->parent;
2102 innerunique = create_unique_path(root,
2104 innerrel->cheapest_total_path);
2105 if (innerunique->rows >= innerrel->rows)
2109 * Compute same result set_joinrel_size_estimates would compute for
2110 * JOIN_INNER. Note that we use the input rels' absolute size estimates,
2111 * not PATH_ROWS() which might be less; if we used PATH_ROWS() we'd be
2112 * double-counting the effects of any join clauses used in input scans.
2114 selec = clauselist_selectivity(root,
2115 path->joinrestrictinfo,
2118 nrows = path->outerjoinpath->parent->rows * innerrel->rows * selec;
2120 nrows = clamp_row_est(nrows);
2122 /* See if it's larger than the actual JOIN_IN size estimate */
2123 if (nrows > path->path.parent->rows)
2124 return path->path.parent->rows / nrows;
2130 * set_function_size_estimates
2131 * Set the size estimates for a base relation that is a function call.
2133 * The rel's targetlist and restrictinfo list must have been constructed
2136 * We set the same fields as set_baserel_size_estimates.
2139 set_function_size_estimates(PlannerInfo *root, RelOptInfo *rel)
2143 /* Should only be applied to base relations that are functions */
2144 Assert(rel->relid > 0);
2145 rte = rt_fetch(rel->relid, root->parse->rtable);
2146 Assert(rte->rtekind == RTE_FUNCTION);
2149 * Estimate number of rows the function itself will return.
2151 * XXX no idea how to do this yet; but we can at least check whether
2152 * function returns set or not...
2154 if (expression_returns_set(rte->funcexpr))
2159 /* Now estimate number of output rows, etc */
2160 set_baserel_size_estimates(root, rel);
2164 * set_values_size_estimates
2165 * Set the size estimates for a base relation that is a values list.
2167 * The rel's targetlist and restrictinfo list must have been constructed
2170 * We set the same fields as set_baserel_size_estimates.
2173 set_values_size_estimates(PlannerInfo *root, RelOptInfo *rel)
2177 /* Should only be applied to base relations that are values lists */
2178 Assert(rel->relid > 0);
2179 rte = rt_fetch(rel->relid, root->parse->rtable);
2180 Assert(rte->rtekind == RTE_VALUES);
2183 * Estimate number of rows the values list will return. We know this
2184 * precisely based on the list length (well, barring set-returning
2185 * functions in list items, but that's a refinement not catered for
2186 * anywhere else either).
2188 rel->tuples = list_length(rte->values_lists);
2190 /* Now estimate number of output rows, etc */
2191 set_baserel_size_estimates(root, rel);
2197 * Set the estimated output width of a base relation.
2199 * NB: this works best on plain relations because it prefers to look at
2200 * real Vars. It will fail to make use of pg_statistic info when applied
2201 * to a subquery relation, even if the subquery outputs are simple vars
2202 * that we could have gotten info for. Is it worth trying to be smarter
2205 * The per-attribute width estimates are cached for possible re-use while
2206 * building join relations.
2209 set_rel_width(PlannerInfo *root, RelOptInfo *rel)
2211 int32 tuple_width = 0;
2214 foreach(tllist, rel->reltargetlist)
2216 Var *var = (Var *) lfirst(tllist);
2221 /* For now, punt on whole-row child Vars */
2224 tuple_width += 32; /* arbitrary */
2228 ndx = var->varattno - rel->min_attr;
2231 * The width probably hasn't been cached yet, but may as well check
2233 if (rel->attr_widths[ndx] > 0)
2235 tuple_width += rel->attr_widths[ndx];
2239 relid = getrelid(var->varno, root->parse->rtable);
2240 if (relid != InvalidOid)
2242 item_width = get_attavgwidth(relid, var->varattno);
2245 rel->attr_widths[ndx] = item_width;
2246 tuple_width += item_width;
2252 * Not a plain relation, or can't find statistics for it. Estimate
2253 * using just the type info.
2255 item_width = get_typavgwidth(var->vartype, var->vartypmod);
2256 Assert(item_width > 0);
2257 rel->attr_widths[ndx] = item_width;
2258 tuple_width += item_width;
2260 Assert(tuple_width >= 0);
2261 rel->width = tuple_width;
2265 * relation_byte_size
2266 * Estimate the storage space in bytes for a given number of tuples
2267 * of a given width (size in bytes).
2270 relation_byte_size(double tuples, int width)
2272 return tuples * (MAXALIGN(width) + MAXALIGN(sizeof(HeapTupleHeaderData)));
2277 * Returns an estimate of the number of pages covered by a given
2278 * number of tuples of a given width (size in bytes).
2281 page_size(double tuples, int width)
2283 return ceil(relation_byte_size(tuples, width) / BLCKSZ);