diff --git a/src/backend/utils/adt/selfuncs.c b/src/backend/utils/adt/selfuncs.c
index 6d78068476e520f7dd2da6c0c8d48d93e0649768..5a4fa77848b5e44abd913e536f0f83cc06bb85fb 100644
*** a/src/backend/utils/adt/selfuncs.c
--- b/src/backend/utils/adt/selfuncs.c
***************
*** 110,115 ****
--- 110,116 ----
  #include "optimizer/predtest.h"
  #include "optimizer/restrictinfo.h"
  #include "optimizer/var.h"
+ #include "parser/parse_clause.h"
  #include "parser/parse_coerce.h"
  #include "parser/parsetree.h"
  #include "utils/builtins.h"
*************** examine_simple_variable(PlannerInfo *roo
*** 4357,4375 ****
  	{
  		/*
  		 * Plain subquery (not one that was converted to an appendrel).
- 		 *
- 		 * Punt if subquery uses set operations, GROUP BY, or DISTINCT --- any
- 		 * of these will mash underlying columns' stats beyond recognition.
- 		 * (Set ops are particularly nasty; if we forged ahead, we would
- 		 * return stats relevant to only the leftmost subselect...)
  		 */
  		Query	   *subquery = rte->subquery;
  		RelOptInfo *rel;
  		TargetEntry *ste;
  
  		if (subquery->setOperations ||
! 			subquery->groupClause ||
! 			subquery->distinctClause)
  			return;
  
  		/*
--- 4358,4378 ----
  	{
  		/*
  		 * Plain subquery (not one that was converted to an appendrel).
  		 */
  		Query	   *subquery = rte->subquery;
  		RelOptInfo *rel;
  		TargetEntry *ste;
  
+ 		/*
+ 		 * Punt if subquery uses set operations or GROUP BY, as these will
+ 		 * mash underlying columns' stats beyond recognition.  (Set ops are
+ 		 * particularly nasty; if we forged ahead, we would return stats
+ 		 * relevant to only the leftmost subselect...)  DISTINCT is also
+ 		 * problematic, but we check that later because there is a possibility
+ 		 * of learning something even with it.
+ 		 */
  		if (subquery->setOperations ||
! 			subquery->groupClause)
  			return;
  
  		/*
*************** examine_simple_variable(PlannerInfo *roo
*** 4415,4420 ****
--- 4418,4437 ----
  				 rte->eref->aliasname, var->varattno);
  		var = (Var *) ste->expr;
  
+ 		/*
+ 		 * If subquery uses DISTINCT, we can't make use of any stats for the
+ 		 * variable ... but, if it's the only DISTINCT column, we are entitled
+ 		 * to consider it unique.  We do the test this way so that it works
+ 		 * for cases involving DISTINCT ON.
+ 		 */
+ 		if (subquery->distinctClause)
+ 		{
+ 			if (list_length(subquery->distinctClause) == 1 &&
+ 				targetIsInSortList(ste, InvalidOid, subquery->distinctClause))
+ 				vardata->isunique = true;
+ 			return;
+ 		}
+ 
  		/* Can only handle a simple Var of subquery's query level */
  		if (var && IsA(var, Var) &&
  			var->varlevelsup == 0)
