diff --git a/src/backend/optimizer/path/costsize.c b/src/backend/optimizer/path/costsize.c index 659daa2..b85b001 100644 --- a/src/backend/optimizer/path/costsize.c +++ b/src/backend/optimizer/path/costsize.c @@ -454,6 +454,34 @@ cost_index(IndexPath *path, PlannerInfo *root, double loop_count) path->path.startup_cost = startup_cost; path->path.total_cost = startup_cost + run_cost; + + /* + * If we have no indexquals then we guesstimate that the startup + * cost will be half of the total cost of the query. + * + * This is a risk-weighted viewpoint; we don't know an accurate + * value because we don't keep statistics in sufficient detail. + * The minimum startup cost could be almost zero, whereas the + * maximum startup cost would be paid when we had to scan the + * whole index before we found any tuples. The worst case is + * frequently seen in practice, e.g. where scans search + * for data not present within the table or where the user + * requests LIMIT 10 but there are only 9 matching tuples. + * + * It might occur to you that we could get a better value for + * the startup cost if we had correlation statistics between + * columns. That would still be only an estimate since the + * distribution of values does vary wildly in practice, based + * upon specific values. e.g. finding the last 10 events from + * a specific user varies considerably depending upon the user. + * + * The main effect of this is that it prevents a LIMIT clause + * from reducing the cost of index scans without quals, + * however this heuristic is our best principled estimate + * of the true startup cost, not just a hack to make LIMIT work. + */ + if (path->indexquals == NIL) + path->path.startup_cost = path->path.total_cost / 2.0; } /*