1 /*-------------------------------------------------------------------------
4 * Routines to compute (and set) relation sizes and path costs
6 * Path costs are measured in units of disk accesses: one sequential page
7 * fetch has cost 1. All else is scaled relative to a page fetch, using
8 * the scaling parameters
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 process a typical WHERE operator
15 * We also use a rough estimate "effective_cache_size" of the number of
16 * disk pages in Postgres + OS-level disk cache. (We can't simply use
17 * NBuffers for this purpose because that would ignore the effects of
18 * the kernel's disk cache.)
20 * Obviously, taking constants for these values is an oversimplification,
21 * but it's tough enough to get any useful estimates even at this level of
22 * detail. Note that all of these parameters are user-settable, in case
23 * the default values are drastically off for a particular platform.
25 * We compute two separate costs for each path:
26 * total_cost: total estimated cost to fetch all tuples
27 * startup_cost: cost that is expended before first tuple is fetched
28 * In some scenarios, such as when there is a LIMIT or we are implementing
29 * an EXISTS(...) sub-select, it is not necessary to fetch all tuples of the
30 * path's result. A caller can estimate the cost of fetching a partial
31 * result by interpolating between startup_cost and total_cost. In detail:
32 * actual_cost = startup_cost +
33 * (total_cost - startup_cost) * tuples_to_fetch / path->parent->rows;
34 * Note that a relation's rows count (and, by extension, a Plan's plan_rows)
35 * are set without regard to any LIMIT, so that this equation works properly.
36 * (Also, these routines guarantee not to set the rows count to zero, so there
37 * will be no zero divide.) The LIMIT is applied as a separate Plan node.
40 * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group
41 * Portions Copyright (c) 1994, Regents of the University of California
44 * $Header: /cvsroot/pgsql/src/backend/optimizer/path/costsize.c,v 1.72 2001/05/09 00:35:09 tgl Exp $
46 *-------------------------------------------------------------------------
53 #include "catalog/pg_statistic.h"
54 #include "executor/nodeHash.h"
55 #include "miscadmin.h"
56 #include "optimizer/clauses.h"
57 #include "optimizer/cost.h"
58 #include "optimizer/pathnode.h"
59 #include "parser/parsetree.h"
60 #include "utils/lsyscache.h"
61 #include "utils/syscache.h"
64 #define LOG2(x) (log(x) / 0.693147180559945)
65 #define LOG6(x) (log(x) / 1.79175946922805)
68 double effective_cache_size = DEFAULT_EFFECTIVE_CACHE_SIZE;
69 double random_page_cost = DEFAULT_RANDOM_PAGE_COST;
70 double cpu_tuple_cost = DEFAULT_CPU_TUPLE_COST;
71 double cpu_index_tuple_cost = DEFAULT_CPU_INDEX_TUPLE_COST;
72 double cpu_operator_cost = DEFAULT_CPU_OPERATOR_COST;
74 Cost disable_cost = 100000000.0;
76 bool enable_seqscan = true;
77 bool enable_indexscan = true;
78 bool enable_tidscan = true;
79 bool enable_sort = true;
80 bool enable_nestloop = true;
81 bool enable_mergejoin = true;
82 bool enable_hashjoin = true;
85 static bool cost_qual_eval_walker(Node *node, Cost *total);
86 static void set_rel_width(Query *root, RelOptInfo *rel);
87 static double relation_byte_size(double tuples, int width);
88 static double page_size(double tuples, int width);
93 * Determines and returns the cost of scanning a relation sequentially.
95 * Note: for historical reasons, this routine and the others in this module
96 * use the passed result Path only to store their startup_cost and total_cost
97 * results into. All the input data they need is passed as separate
98 * parameters, even though much of it could be extracted from the Path.
101 cost_seqscan(Path *path, RelOptInfo *baserel)
103 Cost startup_cost = 0;
107 /* Should only be applied to base relations */
108 Assert(length(baserel->relids) == 1);
109 Assert(!baserel->issubquery);
112 startup_cost += disable_cost;
117 * The cost of reading a page sequentially is 1.0, by definition. Note
118 * that the Unix kernel will typically do some amount of read-ahead
119 * optimization, so that this cost is less than the true cost of
120 * reading a page from disk. We ignore that issue here, but must take
121 * it into account when estimating the cost of non-sequential
124 run_cost += baserel->pages; /* sequential fetches with cost 1.0 */
127 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost;
128 run_cost += cpu_per_tuple * baserel->tuples;
130 path->startup_cost = startup_cost;
131 path->total_cost = startup_cost + run_cost;
135 * cost_nonsequential_access
136 * Estimate the cost of accessing one page at random from a relation
137 * (or sort temp file) of the given size in pages.
139 * The simplistic model that the cost is random_page_cost is what we want
140 * to use for large relations; but for small ones that is a serious
141 * overestimate because of the effects of caching. This routine tries to
144 * Unfortunately we don't have any good way of estimating the effective cache
145 * size we are working with --- we know that Postgres itself has NBuffers
146 * internal buffers, but the size of the kernel's disk cache is uncertain,
147 * and how much of it we get to use is even less certain. We punt the problem
148 * for now by assuming we are given an effective_cache_size parameter.
150 * Given a guesstimated cache size, we estimate the actual I/O cost per page
151 * with the entirely ad-hoc equations:
152 * for rel_size <= effective_cache_size:
153 * 1 + (random_page_cost/2-1) * (rel_size/effective_cache_size) ** 2
154 * for rel_size >= effective_cache_size:
155 * random_page_cost * (1 - (effective_cache_size/rel_size)/2)
156 * These give the right asymptotic behavior (=> 1.0 as rel_size becomes
157 * small, => random_page_cost as it becomes large) and meet in the middle
158 * with the estimate that the cache is about 50% effective for a relation
159 * of the same size as effective_cache_size. (XXX this is probably all
160 * wrong, but I haven't been able to find any theory about how effective
161 * a disk cache should be presumed to be.)
164 cost_nonsequential_access(double relpages)
168 /* don't crash on bad input data */
169 if (relpages <= 0.0 || effective_cache_size <= 0.0)
170 return random_page_cost;
172 relsize = relpages / effective_cache_size;
175 return random_page_cost * (1.0 - 0.5 / relsize);
177 return 1.0 + (random_page_cost * 0.5 - 1.0) * relsize * relsize;
182 * Determines and returns the cost of scanning a relation using an index.
184 * NOTE: an indexscan plan node can actually represent several passes,
185 * but here we consider the cost of just one pass.
187 * 'root' is the query root
188 * 'baserel' is the base relation the index is for
189 * 'index' is the index to be used
190 * 'indexQuals' is the list of applicable qual clauses (implicit AND semantics)
191 * 'is_injoin' is T if we are considering using the index scan as the inside
192 * of a nestloop join (hence, some of the indexQuals are join clauses)
194 * NOTE: 'indexQuals' must contain only clauses usable as index restrictions.
195 * Any additional quals evaluated as qpquals may reduce the number of returned
196 * tuples, but they won't reduce the number of tuples we have to fetch from
197 * the table, so they don't reduce the scan cost.
200 cost_index(Path *path, Query *root,
206 Cost startup_cost = 0;
209 Cost indexStartupCost;
211 Selectivity indexSelectivity;
212 double tuples_fetched;
213 double pages_fetched;
215 /* Should only be applied to base relations */
216 Assert(IsA(baserel, RelOptInfo) &&IsA(index, IndexOptInfo));
217 Assert(length(baserel->relids) == 1);
218 Assert(!baserel->issubquery);
220 if (!enable_indexscan && !is_injoin)
221 startup_cost += disable_cost;
224 * Call index-access-method-specific code to estimate the processing
225 * cost for scanning the index, as well as the selectivity of the
226 * index (ie, the fraction of main-table tuples we will have to
229 OidFunctionCall7(index->amcostestimate,
230 PointerGetDatum(root),
231 PointerGetDatum(baserel),
232 PointerGetDatum(index),
233 PointerGetDatum(indexQuals),
234 PointerGetDatum(&indexStartupCost),
235 PointerGetDatum(&indexTotalCost),
236 PointerGetDatum(&indexSelectivity));
238 /* all costs for touching index itself included here */
239 startup_cost += indexStartupCost;
240 run_cost += indexTotalCost - indexStartupCost;
243 * Estimate number of main-table tuples and pages fetched.
245 * If the number of tuples is much smaller than the number of pages in
246 * the relation, each tuple will cost a separate nonsequential fetch.
247 * If it is comparable or larger, then probably we will be able to
248 * avoid some fetches. We use a growth rate of log(#tuples/#pages +
249 * 1) --- probably totally bogus, but intuitively it gives the right
250 * shape of curve at least.
252 * XXX if the relation has recently been "clustered" using this index,
253 * then in fact the target tuples will be highly nonuniformly
254 * distributed, and we will be seriously overestimating the scan cost!
255 * Currently we have no way to know whether the relation has been
256 * clustered, nor how much it's been modified since the last
257 * clustering, so we ignore this effect. Would be nice to do better
261 tuples_fetched = indexSelectivity * baserel->tuples;
262 /* Don't believe estimates less than 1... */
263 if (tuples_fetched < 1.0)
264 tuples_fetched = 1.0;
266 if (baserel->pages > 0)
267 pages_fetched = ceil(baserel->pages *
268 log(tuples_fetched / baserel->pages + 1.0));
270 pages_fetched = tuples_fetched;
273 * Now estimate one nonsequential access per page fetched, plus
274 * appropriate CPU costs per tuple.
277 /* disk costs for main table */
278 run_cost += pages_fetched * cost_nonsequential_access(baserel->pages);
281 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost;
284 * Normally the indexquals will be removed from the list of
285 * restriction clauses that we have to evaluate as qpquals, so we
286 * should subtract their costs from baserestrictcost. For a lossy
287 * index, however, we will have to recheck all the quals and so
288 * mustn't subtract anything. Also, if we are doing a join then some
289 * of the indexquals are join clauses and shouldn't be subtracted.
290 * Rather than work out exactly how much to subtract, we don't
291 * subtract anything in that case either.
293 if (!index->lossy && !is_injoin)
294 cpu_per_tuple -= cost_qual_eval(indexQuals);
296 run_cost += cpu_per_tuple * tuples_fetched;
298 path->startup_cost = startup_cost;
299 path->total_cost = startup_cost + run_cost;
304 * Determines and returns the cost of scanning a relation using tid-s.
307 cost_tidscan(Path *path, RelOptInfo *baserel, List *tideval)
309 Cost startup_cost = 0;
312 int ntuples = length(tideval);
315 startup_cost += disable_cost;
317 /* disk costs --- assume each tuple on a different page */
318 run_cost += random_page_cost * ntuples;
321 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost;
322 run_cost += cpu_per_tuple * ntuples;
324 path->startup_cost = startup_cost;
325 path->total_cost = startup_cost + run_cost;
330 * Determines and returns the cost of sorting a relation.
332 * The cost of supplying the input data is NOT included; the caller should
333 * add that cost to both startup and total costs returned from this routine!
335 * If the total volume of data to sort is less than SortMem, we will do
336 * an in-memory sort, which requires no I/O and about t*log2(t) tuple
337 * comparisons for t tuples.
339 * If the total volume exceeds SortMem, we switch to a tape-style merge
340 * algorithm. There will still be about t*log2(t) tuple comparisons in
341 * total, but we will also need to write and read each tuple once per
342 * merge pass. We expect about ceil(log6(r)) merge passes where r is the
343 * number of initial runs formed (log6 because tuplesort.c uses six-tape
344 * merging). Since the average initial run should be about twice SortMem,
346 * disk traffic = 2 * relsize * ceil(log6(p / (2*SortMem)))
347 * cpu = comparison_cost * t * log2(t)
349 * The disk traffic is assumed to be half sequential and half random
350 * accesses (XXX can't we refine that guess?)
352 * We charge two operator evals per tuple comparison, which should be in
353 * the right ballpark in most cases.
355 * 'pathkeys' is a list of sort keys
356 * 'tuples' is the number of tuples in the relation
357 * 'width' is the average tuple width in bytes
359 * NOTE: some callers currently pass NIL for pathkeys because they
360 * can't conveniently supply the sort keys. Since this routine doesn't
361 * currently do anything with pathkeys anyway, that doesn't matter...
362 * but if it ever does, it should react gracefully to lack of key data.
365 cost_sort(Path *path, List *pathkeys, double tuples, int width)
367 Cost startup_cost = 0;
369 double nbytes = relation_byte_size(tuples, width);
370 long sortmembytes = SortMem * 1024L;
373 startup_cost += disable_cost;
376 * We want to be sure the cost of a sort is never estimated as zero,
377 * even if passed-in tuple count is zero. Besides, mustn't do
386 * Assume about two operator evals per tuple comparison and N log2 N
389 startup_cost += 2.0 * cpu_operator_cost * tuples * LOG2(tuples);
392 if (nbytes > sortmembytes)
394 double npages = ceil(nbytes / BLCKSZ);
395 double nruns = nbytes / (sortmembytes * 2);
396 double log_runs = ceil(LOG6(nruns));
397 double npageaccesses;
401 npageaccesses = 2.0 * npages * log_runs;
402 /* Assume half are sequential (cost 1), half are not */
403 startup_cost += npageaccesses *
404 (1.0 + cost_nonsequential_access(npages)) * 0.5;
408 * Note: should we bother to assign a nonzero run_cost to reflect the
409 * overhead of extracting tuples from the sort result? Probably not
410 * worth worrying about.
412 path->startup_cost = startup_cost;
413 path->total_cost = startup_cost + run_cost;
419 * Determines and returns the cost of joining two relations using the
420 * nested loop algorithm.
422 * 'outer_path' is the path for the outer relation
423 * 'inner_path' is the path for the inner relation
424 * 'restrictlist' are the RestrictInfo nodes to be applied at the join
427 cost_nestloop(Path *path,
432 Cost startup_cost = 0;
437 if (!enable_nestloop)
438 startup_cost += disable_cost;
440 /* cost of source data */
443 * NOTE: clearly, we must pay both outer and inner paths' startup_cost
444 * before we can start returning tuples, so the join's startup cost
445 * is their sum. What's not so clear is whether the inner path's
446 * startup_cost must be paid again on each rescan of the inner path.
447 * This is not true if the inner path is materialized, but probably
448 * is true otherwise. Since we don't yet have clean handling of the
449 * decision whether to materialize a path, we can't tell here which
450 * will happen. As a compromise, charge 50% of the inner startup cost
453 startup_cost += outer_path->startup_cost + inner_path->startup_cost;
454 run_cost += outer_path->total_cost - outer_path->startup_cost;
455 run_cost += outer_path->parent->rows *
456 (inner_path->total_cost - inner_path->startup_cost);
457 if (outer_path->parent->rows > 1)
458 run_cost += (outer_path->parent->rows - 1) * inner_path->startup_cost;
461 * Number of tuples processed (not number emitted!). If inner path is
462 * an indexscan, be sure to use its estimated output row count, which
463 * may be lower than the restriction-clause-only row count of its
466 if (IsA(inner_path, IndexPath))
467 ntuples = ((IndexPath *) inner_path)->rows;
469 ntuples = inner_path->parent->rows;
470 ntuples *= outer_path->parent->rows;
473 cpu_per_tuple = cpu_tuple_cost + cost_qual_eval(restrictlist);
474 run_cost += cpu_per_tuple * ntuples;
476 path->startup_cost = startup_cost;
477 path->total_cost = startup_cost + run_cost;
482 * Determines and returns the cost of joining two relations using the
483 * merge join algorithm.
485 * 'outer_path' is the path for the outer relation
486 * 'inner_path' is the path for the inner relation
487 * 'restrictlist' are the RestrictInfo nodes to be applied at the join
488 * 'outersortkeys' and 'innersortkeys' are lists of the keys to be used
489 * to sort the outer and inner relations, or NIL if no explicit
490 * sort is needed because the source path is already ordered
493 cost_mergejoin(Path *path,
500 Cost startup_cost = 0;
504 Path sort_path; /* dummy for result of cost_sort */
506 if (!enable_mergejoin)
507 startup_cost += disable_cost;
509 /* cost of source data */
512 * Note we are assuming that each source tuple is fetched just once,
513 * which is not right in the presence of equal keys. If we had a way
514 * of estimating the proportion of equal keys, we could apply a
515 * correction factor...
517 if (outersortkeys) /* do we need to sort outer? */
519 startup_cost += outer_path->total_cost;
520 cost_sort(&sort_path,
522 outer_path->parent->rows,
523 outer_path->parent->width);
524 startup_cost += sort_path.startup_cost;
525 run_cost += sort_path.total_cost - sort_path.startup_cost;
529 startup_cost += outer_path->startup_cost;
530 run_cost += outer_path->total_cost - outer_path->startup_cost;
533 if (innersortkeys) /* do we need to sort inner? */
535 startup_cost += inner_path->total_cost;
536 cost_sort(&sort_path,
538 inner_path->parent->rows,
539 inner_path->parent->width);
540 startup_cost += sort_path.startup_cost;
541 run_cost += sort_path.total_cost - sort_path.startup_cost;
545 startup_cost += inner_path->startup_cost;
546 run_cost += inner_path->total_cost - inner_path->startup_cost;
550 * Estimate the number of tuples to be processed in the mergejoin
551 * itself as one per tuple in the two source relations. This could be
552 * a drastic underestimate if there are many equal-keyed tuples in
553 * either relation, but we have no good way of estimating that...
555 ntuples = outer_path->parent->rows + inner_path->parent->rows;
558 cpu_per_tuple = cpu_tuple_cost + cost_qual_eval(restrictlist);
559 run_cost += cpu_per_tuple * ntuples;
561 path->startup_cost = startup_cost;
562 path->total_cost = startup_cost + run_cost;
567 * Determines and returns the cost of joining two relations using the
568 * hash join algorithm.
570 * 'outer_path' is the path for the outer relation
571 * 'inner_path' is the path for the inner relation
572 * 'restrictlist' are the RestrictInfo nodes to be applied at the join
573 * 'innerbucketsize' is an estimate of the bucketsize statistic
574 * for the inner hash key.
577 cost_hashjoin(Path *path,
581 Selectivity innerbucketsize)
583 Cost startup_cost = 0;
587 double outerbytes = relation_byte_size(outer_path->parent->rows,
588 outer_path->parent->width);
589 double innerbytes = relation_byte_size(inner_path->parent->rows,
590 inner_path->parent->width);
591 long hashtablebytes = SortMem * 1024L;
593 if (!enable_hashjoin)
594 startup_cost += disable_cost;
596 /* cost of source data */
597 startup_cost += outer_path->startup_cost;
598 run_cost += outer_path->total_cost - outer_path->startup_cost;
599 startup_cost += inner_path->total_cost;
601 /* cost of computing hash function: must do it once per input tuple */
602 startup_cost += cpu_operator_cost * inner_path->parent->rows;
603 run_cost += cpu_operator_cost * outer_path->parent->rows;
606 * The number of tuple comparisons needed is the number of outer
607 * tuples times the typical number of tuples in a hash bucket,
608 * which is the inner relation size times its bucketsize fraction.
609 * We charge one cpu_operator_cost per tuple comparison.
611 run_cost += cpu_operator_cost * outer_path->parent->rows *
612 ceil(inner_path->parent->rows * innerbucketsize);
615 * Estimate the number of tuples that get through the hashing filter
616 * as one per tuple in the two source relations. This could be a
617 * drastic underestimate if there are many equal-keyed tuples in
618 * either relation, but we have no simple way of estimating that;
619 * and since this is only a second-order parameter, it's probably
620 * not worth expending a lot of effort on the estimate.
622 ntuples = outer_path->parent->rows + inner_path->parent->rows;
625 cpu_per_tuple = cpu_tuple_cost + cost_qual_eval(restrictlist);
626 run_cost += cpu_per_tuple * ntuples;
629 * if inner relation is too big then we will need to "batch" the join,
630 * which implies writing and reading most of the tuples to disk an
631 * extra time. Charge one cost unit per page of I/O (correct since it
632 * should be nice and sequential...). Writing the inner rel counts as
633 * startup cost, all the rest as run cost.
635 if (innerbytes > hashtablebytes)
637 double outerpages = page_size(outer_path->parent->rows,
638 outer_path->parent->width);
639 double innerpages = page_size(inner_path->parent->rows,
640 inner_path->parent->width);
642 startup_cost += innerpages;
643 run_cost += innerpages + 2 * outerpages;
647 * Bias against putting larger relation on inside. We don't want an
648 * absolute prohibition, though, since larger relation might have
649 * better bucketsize --- and we can't trust the size estimates
650 * unreservedly, anyway. Instead, inflate the startup cost by the
651 * square root of the size ratio. (Why square root? No real good
652 * reason, but it seems reasonable...)
654 if (innerbytes > outerbytes && outerbytes > 0)
655 startup_cost *= sqrt(innerbytes / outerbytes);
657 path->startup_cost = startup_cost;
658 path->total_cost = startup_cost + run_cost;
662 * Estimate hash bucketsize fraction (ie, number of entries in a bucket
663 * divided by total tuples in relation) if the specified Var is used
666 * This statistic is used by cost_hashjoin. We split out the calculation
667 * because it's useful to cache the result for re-use across multiple path
670 * XXX This is really pretty bogus since we're effectively assuming that the
671 * distribution of hash keys will be the same after applying restriction
672 * clauses as it was in the underlying relation. However, we are not nearly
673 * smart enough to figure out how the restrict clauses might change the
674 * distribution, so this will have to do for now.
676 * The executor tries for average bucket loading of NTUP_PER_BUCKET by setting
677 * number of buckets equal to ntuples / NTUP_PER_BUCKET, which would yield
678 * a bucketsize fraction of NTUP_PER_BUCKET / ntuples. But that goal will
679 * be reached only if the data values are uniformly distributed among the
680 * buckets, which requires (a) at least ntuples / NTUP_PER_BUCKET distinct
681 * data values, and (b) a not-too-skewed data distribution. Otherwise the
682 * buckets will be nonuniformly occupied. If the other relation in the join
683 * has a similar distribution, the most-loaded buckets are exactly those
684 * that will be probed most often. Therefore, the "average" bucket size for
685 * costing purposes should really be taken as something close to the "worst
686 * case" bucket size. We try to estimate this by first scaling up if there
687 * are too few distinct data values, and then scaling up again by the
688 * ratio of the most common value's frequency to the average frequency.
690 * If no statistics are available, use a default estimate of 0.1. This will
691 * discourage use of a hash rather strongly if the inner relation is large,
692 * which is what we want. We do not want to hash unless we know that the
693 * inner rel is well-dispersed (or the alternatives seem much worse).
696 estimate_hash_bucketsize(Query *root, Var *var)
701 Form_pg_statistic stats;
711 * Lookup info about var's relation and attribute;
712 * if none available, return default estimate.
717 relid = getrelid(var->varno, root->rtable);
718 if (relid == InvalidOid)
721 rel = get_base_rel(root, var->varno);
723 if (rel->tuples <= 0.0 || rel->rows <= 0.0)
724 return 0.1; /* ensure we can divide below */
726 tuple = SearchSysCache(STATRELATT,
727 ObjectIdGetDatum(relid),
728 Int16GetDatum(var->varattno),
730 if (!HeapTupleIsValid(tuple))
733 * Perhaps the Var is a system attribute; if so, it will have no
734 * entry in pg_statistic, but we may be able to guess something
735 * about its distribution anyway.
737 switch (var->varattno)
739 case ObjectIdAttributeNumber:
740 case SelfItemPointerAttributeNumber:
741 /* these are unique, so buckets should be well-distributed */
742 return (double) NTUP_PER_BUCKET / rel->rows;
743 case TableOidAttributeNumber:
744 /* hashing this is a terrible idea... */
749 stats = (Form_pg_statistic) GETSTRUCT(tuple);
752 * Obtain number of distinct data values in raw relation.
754 ndistinct = stats->stadistinct;
756 ndistinct = -ndistinct * rel->tuples;
759 * Adjust ndistinct to account for restriction clauses. Observe we are
760 * assuming that the data distribution is affected uniformly by the
761 * restriction clauses!
763 * XXX Possibly better way, but much more expensive: multiply by
764 * selectivity of rel's restriction clauses that mention the target Var.
766 ndistinct *= rel->rows / rel->tuples;
769 * Discourage use of hash join if there seem not to be very many distinct
770 * data values. The threshold here is somewhat arbitrary, as is the
771 * fraction used to "discourage" the choice.
773 if (ndistinct < 50.0)
775 ReleaseSysCache(tuple);
780 * Form initial estimate of bucketsize fraction. Here we use rel->rows,
781 * ie the number of rows after applying restriction clauses, because
782 * that's what the fraction will eventually be multiplied by in
785 estfract = (double) NTUP_PER_BUCKET / rel->rows;
788 * Adjust estimated bucketsize if too few distinct values to fill
791 needdistinct = rel->rows / (double) NTUP_PER_BUCKET;
792 if (ndistinct < needdistinct)
793 estfract *= needdistinct / ndistinct;
796 * Look up the frequency of the most common value, if available.
800 if (get_attstatsslot(tuple, var->vartype, var->vartypmod,
801 STATISTIC_KIND_MCV, InvalidOid,
802 NULL, NULL, &numbers, &nnumbers))
805 * The first MCV stat is for the most common value.
808 mcvfreq = numbers[0];
809 free_attstatsslot(var->vartype, NULL, 0,
814 * Adjust estimated bucketsize upward to account for skewed distribution.
816 avgfreq = (1.0 - stats->stanullfrac) / ndistinct;
818 if (avgfreq > 0.0 && mcvfreq > avgfreq)
819 estfract *= mcvfreq / avgfreq;
821 ReleaseSysCache(tuple);
823 return (Selectivity) estfract;
829 * Estimate the CPU cost of evaluating a WHERE clause (once).
830 * The input can be either an implicitly-ANDed list of boolean
831 * expressions, or a list of RestrictInfo nodes.
834 cost_qual_eval(List *quals)
839 /* We don't charge any cost for the implicit ANDing at top level ... */
843 Node *qual = (Node *) lfirst(l);
846 * RestrictInfo nodes contain an eval_cost field reserved for this
847 * routine's use, so that it's not necessary to evaluate the qual
848 * clause's cost more than once. If the clause's cost hasn't been
849 * computed yet, the field will contain -1.
851 if (qual && IsA(qual, RestrictInfo))
853 RestrictInfo *restrictinfo = (RestrictInfo *) qual;
855 if (restrictinfo->eval_cost < 0)
857 restrictinfo->eval_cost = 0;
858 cost_qual_eval_walker((Node *) restrictinfo->clause,
859 &restrictinfo->eval_cost);
861 total += restrictinfo->eval_cost;
865 /* If it's a bare expression, must always do it the hard way */
866 cost_qual_eval_walker(qual, &total);
873 cost_qual_eval_walker(Node *node, Cost *total)
879 * Our basic strategy is to charge one cpu_operator_cost for each
880 * operator or function node in the given tree. Vars and Consts are
881 * charged zero, and so are boolean operators (AND, OR, NOT).
882 * Simplistic, but a lot better than no model at all.
884 * Should we try to account for the possibility of short-circuit
885 * evaluation of AND/OR?
889 Expr *expr = (Expr *) node;
891 switch (expr->opType)
895 *total += cpu_operator_cost;
904 * A subplan node in an expression indicates that the
905 * subplan will be executed on each evaluation, so charge
906 * accordingly. (We assume that sub-selects that can be
907 * executed as InitPlans have already been removed from
910 * NOTE: this logic should agree with the estimates used by
911 * make_subplan() in plan/subselect.c.
914 SubPlan *subplan = (SubPlan *) expr->oper;
915 Plan *plan = subplan->plan;
918 if (subplan->sublink->subLinkType == EXISTS_SUBLINK)
920 /* we only need to fetch 1 tuple */
921 subcost = plan->startup_cost +
922 (plan->total_cost - plan->startup_cost) / plan->plan_rows;
924 else if (subplan->sublink->subLinkType == ALL_SUBLINK ||
925 subplan->sublink->subLinkType == ANY_SUBLINK)
927 /* assume we need 50% of the tuples */
928 subcost = plan->startup_cost +
929 0.50 * (plan->total_cost - plan->startup_cost);
930 /* XXX what if subplan has been materialized? */
934 /* assume we need all tuples */
935 subcost = plan->total_cost;
941 /* fall through to examine args of Expr node */
943 return expression_tree_walker(node, cost_qual_eval_walker,
949 * set_baserel_size_estimates
950 * Set the size estimates for the given base relation.
952 * The rel's targetlist and restrictinfo list must have been constructed
955 * We set the following fields of the rel node:
956 * rows: the estimated number of output tuples (after applying
957 * restriction clauses).
958 * width: the estimated average output tuple width in bytes.
959 * baserestrictcost: estimated cost of evaluating baserestrictinfo clauses.
962 set_baserel_size_estimates(Query *root, RelOptInfo *rel)
964 /* Should only be applied to base relations */
965 Assert(length(rel->relids) == 1);
967 rel->rows = rel->tuples *
968 restrictlist_selectivity(root,
969 rel->baserestrictinfo,
970 lfirsti(rel->relids));
973 * Force estimate to be at least one row, to make explain output look
974 * better and to avoid possible divide-by-zero when interpolating
980 rel->baserestrictcost = cost_qual_eval(rel->baserestrictinfo);
982 set_rel_width(root, rel);
986 * set_joinrel_size_estimates
987 * Set the size estimates for the given join relation.
989 * The rel's targetlist must have been constructed already, and a
990 * restriction clause list that matches the given component rels must
993 * Since there is more than one way to make a joinrel for more than two
994 * base relations, the results we get here could depend on which component
995 * rel pair is provided. In theory we should get the same answers no matter
996 * which pair is provided; in practice, since the selectivity estimation
997 * routines don't handle all cases equally well, we might not. But there's
998 * not much to be done about it. (Would it make sense to repeat the
999 * calculations for each pair of input rels that's encountered, and somehow
1000 * average the results? Probably way more trouble than it's worth.)
1002 * We set the same relnode fields as set_baserel_size_estimates() does.
1005 set_joinrel_size_estimates(Query *root, RelOptInfo *rel,
1006 RelOptInfo *outer_rel,
1007 RelOptInfo *inner_rel,
1013 /* Start with the Cartesian product */
1014 temp = outer_rel->rows * inner_rel->rows;
1017 * Apply join restrictivity. Note that we are only considering
1018 * clauses that become restriction clauses at this join level; we are
1019 * not double-counting them because they were not considered in
1020 * estimating the sizes of the component rels.
1022 temp *= restrictlist_selectivity(root,
1027 * If we are doing an outer join, take that into account: the output
1028 * must be at least as large as the non-nullable input. (Is there any
1029 * chance of being even smarter?)
1036 if (temp < outer_rel->rows)
1037 temp = outer_rel->rows;
1040 if (temp < inner_rel->rows)
1041 temp = inner_rel->rows;
1044 if (temp < outer_rel->rows)
1045 temp = outer_rel->rows;
1046 if (temp < inner_rel->rows)
1047 temp = inner_rel->rows;
1050 elog(ERROR, "set_joinrel_size_estimates: unsupported join type %d",
1056 * Force estimate to be at least one row, to make explain output look
1057 * better and to avoid possible divide-by-zero when interpolating
1066 * We could apply set_rel_width() to compute the output tuple width
1067 * from scratch, but at present it's always just the sum of the input
1068 * widths, so why work harder than necessary? If relnode.c is ever
1069 * taught to remove unneeded columns from join targetlists, go back to
1070 * using set_rel_width here.
1072 rel->width = outer_rel->width + inner_rel->width;
1077 * Set the estimated output width of the relation.
1079 * NB: this works best on base relations because it prefers to look at
1080 * real Vars. It will fail to make use of pg_statistic info when applied
1081 * to a subquery relation, even if the subquery outputs are simple vars
1082 * that we could have gotten info for. Is it worth trying to be smarter
1086 set_rel_width(Query *root, RelOptInfo *rel)
1088 int32 tuple_width = 0;
1091 foreach(tllist, rel->targetlist)
1093 TargetEntry *tle = (TargetEntry *) lfirst(tllist);
1097 * If it's a Var, try to get statistical info from pg_statistic.
1099 if (tle->expr && IsA(tle->expr, Var))
1101 Var *var = (Var *) tle->expr;
1104 relid = getrelid(var->varno, root->rtable);
1105 if (relid != InvalidOid)
1107 item_width = get_attavgwidth(relid, var->varattno);
1110 tuple_width += item_width;
1116 * Not a Var, or can't find statistics for it. Estimate using
1117 * just the type info.
1119 item_width = get_typavgwidth(tle->resdom->restype,
1120 tle->resdom->restypmod);
1121 Assert(item_width > 0);
1122 tuple_width += item_width;
1124 Assert(tuple_width >= 0);
1125 rel->width = tuple_width;
1129 * relation_byte_size
1130 * Estimate the storage space in bytes for a given number of tuples
1131 * of a given width (size in bytes).
1134 relation_byte_size(double tuples, int width)
1136 return tuples * ((double) MAXALIGN(width + sizeof(HeapTupleData)));
1141 * Returns an estimate of the number of pages covered by a given
1142 * number of tuples of a given width (size in bytes).
1145 page_size(double tuples, int width)
1147 return ceil(relation_byte_size(tuples, width) / BLCKSZ);