4949 * Portions Copyright (c) 1994, Regents of the University of California
5050 *
5151 * IDENTIFICATION
52- * $Header: /cvsroot/pgsql/src/backend/optimizer/path/costsize.c,v 1.105 2003/02/08 20:20:54 tgl Exp $
52+ * $Header: /cvsroot/pgsql/src/backend/optimizer/path/costsize.c,v 1.106 2003/02/15 21:39:58 tgl Exp $
5353 *
5454 *-------------------------------------------------------------------------
5555 */
@@ -601,6 +601,15 @@ cost_agg(Path *path, Query *root,
601601 *
602602 * We will produce a single output tuple if not grouping,
603603 * and a tuple per group otherwise.
604+ *
605+ * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the
606+ * same total CPU cost, but AGG_SORTED has lower startup cost. If the
607+ * input path is already sorted appropriately, AGG_SORTED should be
608+ * preferred (since it has no risk of memory overflow). This will happen
609+ * as long as the computed total costs are indeed exactly equal --- but
610+ * if there's roundoff error we might do the wrong thing. So be sure
611+ * that the computations below form the same intermediate values in the
612+ * same order.
604613 */
605614if (aggstrategy == AGG_PLAIN )
606615{
@@ -614,15 +623,17 @@ cost_agg(Path *path, Query *root,
614623/* Here we are able to deliver output on-the-fly */
615624startup_cost = input_startup_cost ;
616625total_cost = input_total_cost ;
617- total_cost += cpu_operator_cost * ( input_tuples + numGroups ) * numAggs ;
626+ /* calcs phrased this way to match HASHED case, see note above */
618627total_cost += cpu_operator_cost * input_tuples * numGroupCols ;
628+ total_cost += cpu_operator_cost * input_tuples * numAggs ;
629+ total_cost += cpu_operator_cost * numGroups * numAggs ;
619630}
620631else
621632{
622633/* must be AGG_HASHED */
623634startup_cost = input_total_cost ;
624- startup_cost += cpu_operator_cost * input_tuples * numAggs ;
625635startup_cost += cpu_operator_cost * input_tuples * numGroupCols ;
636+ startup_cost += cpu_operator_cost * input_tuples * numAggs ;
626637total_cost = startup_cost ;
627638total_cost += cpu_operator_cost * numGroups * numAggs ;
628639}