diff --git a/src/backend/optimizer/plan/setrefs.c b/src/backend/optimizer/plan/setrefs.c
index e50624c465..14f378fd98 100644
--- a/src/backend/optimizer/plan/setrefs.c
+++ b/src/backend/optimizer/plan/setrefs.c
@@ -1791,28 +1791,21 @@ fix_alternative_subplan(PlannerInfo *root, AlternativeSubPlan *asplan,
 		Cost		curcost;
 
 		curcost = curplan->startup_cost + num_exec * curplan->per_call_cost;
-		if (bestplan == NULL)
+		if (bestplan == NULL || curcost <= bestcost)
 		{
 			bestplan = curplan;
 			bestcost = curcost;
 		}
-		else if (curcost <= bestcost)
-		{
-			/* drop old bestplan */
-			ListCell   *lc2 = list_nth_cell(root->glob->subplans,
-											bestplan->plan_id - 1);
+	}
 
-			lfirst(lc2) = NULL;
-			bestplan = curplan;
-			bestcost = curcost;
-		}
-		else
+	if (bestplan != NULL)
+	{
+		foreach(lc, asplan->subplans)
 		{
-			/* drop curplan */
-			ListCell   *lc2 = list_nth_cell(root->glob->subplans,
-											curplan->plan_id - 1);
+			SubPlan    *curplan = (SubPlan *) lfirst(lc);
 
-			lfirst(lc2) = NULL;
+			if (curplan != bestplan)
+				curplan = NULL;
 		}
 	}