From 3c18cef5f1cf5c6d3be78b14d39e65e49c9cd9b3 Mon Sep 17 00:00:00 2001
From: "ZizhuanLiu(X-MAN)" <44973863@qq.com>
Date: Fri, 20 Nov 2026 20:34:47 +0800
Subject: [PATCH v3] Fix join selectivity for NULL-safe comparisons and
 ordinary inequality

IS [NOT] DISTINCT FROM join estimates currently reuse ordinary equality
selectivity or its complement, losing the required NULL semantics.
Ordinary <> also overestimates joins with NULLs by complementing equality
over all row pairs instead of only pairs with two non-NULL inputs.
For example, two 1,000-row inputs with an all-NULL inner join column can
produce an estimate of 1,000,000 inequality matches although none exist.

Pass an optional null_safe_compare flag to the recognized built-in
equality and inequality join estimators.  Let E be the existing ordinary
equality pair selectivity, n1/n2 the input NULL fractions, and
B = (1 - n1) * (1 - n2) the fraction of pairs with two non-NULL inputs.
For non-SEMI/ANTI inner and outer join clauses, use:

  eqjoinsel():  =                     E
                IS NOT DISTINCT FROM E + n1 * n2
  neqjoinsel(): <>                    B - E
                IS DISTINCT FROM     1 - E - n1 * n2

Keep the existing algorithms and signatures of eqjoinsel_inner() and
eqjoinsel_semi(), apart from adapting their calls to the extended MCV
matcher.  Apply NULL corrections in eqjoinsel().  Reuse that estimate in
neqjoinsel(), excluding NULL-containing pairs for ordinary <> or taking
the NULL-safe equality complement for IS DISTINCT FROM.

SEMI/ANTI joins use S, the fraction of outer rows with at least one inner
partner, rather than pair selectivity E.  For IS NOT DISTINCT FROM, add
NULL partners to the existing non-NULL equality existence estimate S_eq:

  S = S_eq + n_outer * min(n_inner * N_inner, 1)

Here n_outer/n_inner are the outer/inner NULL fractions, and N_inner is
the effective inner row estimate.  Return S = 0 for a provably empty inner
input, reset S_eq to zero for an all-NULL inner input, and retain the
existing bound based on the inner-join estimate.

For <> and IS DISTINCT FROM, distinctjoinsel_semi() estimates S
separately under ordinary or NULL-safe semantics, rather than simply
complementing equality existence.  Extend the equality MCV matcher with
optional match indices, retaining its hash support, and use those indices
to identify unequal partners among inner MCVs.  Account separately for
NULLs and residual values without modifying the statistics slots or
their frequencies.  Both SEMI/ANTI estimators return S; the existing
caller uses S and 1 - S for SEMI and ANTI output rows, respectively.

Preserve the five-argument API and legacy dispatch for other estimator
procedures.  Select the inequality estimator for IS DISTINCT FROM only
when the equality/inequality pair uses the recognized built-in estimators.

Add regression coverage for NULLs, residual values, absent MCV lists,
single-value and multi-value inner inputs, both operand orders, cross-type
MCV matching, and custom estimator procedures.  Update one existing join
plan whose order changes with the corrected ordinary <> selectivity.

Reported-by: Roope Salmi <rpsalmi@gmail.com>
Diagnosed-by: Richard Guo <guofenglinux@gmail.com>
Co-authored-by: shihao zhong <zhong950419@gmail.com>
Co-authored-by: Rahul Yadav <rahul@rhyadav.dev>
Discussion: https://www.postgresql.org/message-id/flat/17545-a0ca4de888953169%40postgresql.org
CommitFest: https://commitfest.postgresql.org/patch/7396/
---
 src/backend/optimizer/path/clausesel.c    |  72 +++-
 src/backend/optimizer/util/plancat.c      |  40 ++
 src/backend/utils/adt/selfuncs.c          | 468 ++++++++++++++++++++--
 src/include/optimizer/plancat.h           |   6 +
 src/test/regress/expected/join.out        |  10 +-
 src/test/regress/expected/planner_est.out | 331 +++++++++++++++
 src/test/regress/sql/planner_est.sql      | 151 +++++++
 7 files changed, 1034 insertions(+), 44 deletions(-)

diff --git a/src/backend/optimizer/path/clausesel.c b/src/backend/optimizer/path/clausesel.c
index c22cbfc9..a5b1f05d 100644
--- a/src/backend/optimizer/path/clausesel.c
+++ b/src/backend/optimizer/path/clausesel.c
@@ -803,13 +803,31 @@ clause_selectivity_ext(PlannerInfo *root,
 	}
 	else if (is_notclause(clause))
 	{
-		/* inverse of the selectivity of the underlying clause */
-		s1 = 1.0 - clause_selectivity_ext(root,
-										  (Node *) get_notclausearg((Expr *) clause),
-										  varRelid,
-										  jointype,
-										  sjinfo,
-										  use_extended_stats);
+		Node	   *node = (Node *) get_notclausearg((Expr *) clause);
+
+		if (IsA(node, DistinctExpr) &&
+			treat_as_join_clause(root, node, rinfo, varRelid, sjinfo))
+		{
+			DistinctExpr *distinctexpr = (DistinctExpr *) node;
+
+			/* NOT DistinctExpr is IS NOT DISTINCT FROM; its operator is "=". */
+			s1 = nullsafe_join_selectivity(root,
+										   distinctexpr->opno,
+										   distinctexpr->args,
+										   distinctexpr->inputcollid,
+										   jointype,
+										   sjinfo);
+		}
+		else
+		{
+			/* inverse of the selectivity of the underlying clause */
+			s1 = 1.0 - clause_selectivity_ext(root,
+											  node,
+											  varRelid,
+											  jointype,
+											  sjinfo,
+											  use_extended_stats);
+		}
 	}
 	else if (is_andclause(clause))
 	{
@@ -838,15 +856,36 @@ clause_selectivity_ext(PlannerInfo *root,
 	{
 		OpExpr	   *opclause = (OpExpr *) clause;
 		Oid			opno = opclause->opno;
+		Oid			opno_negator = IsA(clause, DistinctExpr) ?
+			get_negator(opno) : InvalidOid;
+		bool		negate = IsA(clause, DistinctExpr);
 
 		if (treat_as_join_clause(root, clause, rinfo, varRelid, sjinfo))
 		{
 			/* Estimate selectivity for a join clause. */
-			s1 = join_selectivity(root, opno,
-								  opclause->args,
-								  opclause->inputcollid,
-								  jointype,
-								  sjinfo);
+			if (IsA(clause, DistinctExpr) && OidIsValid(opno_negator) &&
+				get_oprjoin(opno) == F_EQJOINSEL &&
+				get_oprjoin(opno_negator) == F_NEQJOINSEL)
+			{
+				/*
+				 * DistinctExpr stores "="; use its negator when both
+				 * estimators understand NULL-safe rules.  Otherwise preserve
+				 * the ordinary equality estimate and complement it below.
+				 */
+				s1 = nullsafe_join_selectivity(root,
+											   opno_negator,
+											   opclause->args,
+											   opclause->inputcollid,
+											   jointype,
+											   sjinfo);
+				negate = false;
+			}
+			else
+				s1 = join_selectivity(root, opno,
+									  opclause->args,
+									  opclause->inputcollid,
+									  jointype,
+									  sjinfo);
 		}
 		else
 		{
@@ -859,11 +898,12 @@ clause_selectivity_ext(PlannerInfo *root,
 
 		/*
 		 * DistinctExpr has the same representation as OpExpr, but the
-		 * contained operator is "=" not "<>", so we must negate the result.
-		 * This estimation method doesn't give the right behavior for nulls,
-		 * but it's better than doing nothing.
+		 * contained operator is "=", so negate estimates made through the
+		 * ordinary equality path.  The dedicated join path already uses the
+		 * negator and must not be complemented again.  Restrictions still use
+		 * the ordinary estimate, which does not handle NULLs fully.
 		 */
-		if (IsA(clause, DistinctExpr))
+		if (negate)
 			s1 = 1.0 - s1;
 	}
 	else if (is_funcclause(clause))
diff --git a/src/backend/optimizer/util/plancat.c b/src/backend/optimizer/util/plancat.c
index 22e0e8b1..582e911a 100644
--- a/src/backend/optimizer/util/plancat.c
+++ b/src/backend/optimizer/util/plancat.c
@@ -49,6 +49,7 @@
 #include "storage/bufmgr.h"
 #include "tcop/tcopprot.h"
 #include "utils/builtins.h"
+#include "utils/fmgroids.h"
 #include "utils/lsyscache.h"
 #include "utils/partcache.h"
 #include "utils/rel.h"
@@ -2293,6 +2294,45 @@ join_selectivity(PlannerInfo *root,
 	return (Selectivity) result;
 }
 
+/*
+ * nullsafe_join_selectivity
+ *
+ * Estimate IS [NOT] DISTINCT FROM.  operatorid is the equality operator for
+ * IS NOT DISTINCT FROM and its negator for IS DISTINCT FROM.  Only the built-in
+ * equality and inequality estimators accept the additional NULL-safe flag;
+ * other estimators retain the ordinary join_selectivity calling convention
+ * and their existing estimates, without promising NULL-safe semantics.
+ */
+Selectivity
+nullsafe_join_selectivity(PlannerInfo *root,
+						  Oid operatorid,
+						  List *args,
+						  Oid inputcollid,
+						  JoinType jointype,
+						  SpecialJoinInfo *sjinfo)
+{
+	RegProcedure oprjoin = get_oprjoin(operatorid);
+	float8		result;
+
+	if (oprjoin != F_EQJOINSEL && oprjoin != F_NEQJOINSEL)
+		return join_selectivity(root, operatorid, args, inputcollid,
+								jointype, sjinfo);
+
+	result = DatumGetFloat8(OidFunctionCall6Coll(oprjoin,
+												 inputcollid,
+												 PointerGetDatum(root),
+												 ObjectIdGetDatum(operatorid),
+												 PointerGetDatum(args),
+												 Int16GetDatum(jointype),
+												 PointerGetDatum(sjinfo),
+												 BoolGetDatum(true)));
+
+	if (result < 0.0 || result > 1.0)
+		elog(ERROR, "invalid join selectivity: %f", result);
+
+	return (Selectivity) result;
+}
+
 /*
  * function_selectivity
  *
diff --git a/src/backend/utils/adt/selfuncs.c b/src/backend/utils/adt/selfuncs.c
index 5ee37759..bcb53c0c 100644
--- a/src/backend/utils/adt/selfuncs.c
+++ b/src/backend/utils/adt/selfuncs.c
@@ -210,6 +210,7 @@ static void eqjoinsel_find_matches(FmgrInfo *eqproc, Oid collation,
 								   AttStatsSlot *sslot1, AttStatsSlot *sslot2,
 								   int nvalues1, int nvalues2,
 								   bool *hasmatch1, bool *hasmatch2,
+								   int *matchindex1, int *matchindex2,
 								   int *p_nmatches, double *p_matchprodfreq);
 static uint32 hash_mcv(MCVHashTable_hash *tab, Datum key);
 static bool mcvs_equal(MCVHashTable_hash *tab, Datum key0, Datum key1);
@@ -2381,6 +2382,16 @@ rowcomparesel(PlannerInfo *root,
 
 /*
  *		eqjoinsel		- Join selectivity of "="
+ *
+ * An optional sixth boolean argument, null_safe_compare, enables
+ * IS NOT DISTINCT FROM semantics.
+ * The helper estimators retain ordinary "=" semantics; NULL handling is done
+ * here.  Add the NULL/NULL pair frequency to the inner-join estimate.  For
+ * SEMI/ANTI joins, also estimate the fraction of outer rows that are NULL and
+ * have at least one inner NULL partner.
+ *
+ * neqjoinsel complements this NULL-safe inner-join estimate for IS DISTINCT
+ * FROM inner and outer joins.
  */
 Datum
 eqjoinsel(PG_FUNCTION_ARGS)
@@ -2418,6 +2429,7 @@ eqjoinsel(PG_FUNCTION_ARGS)
 	bool		get_mcv_stats;
 	bool		join_is_reversed;
 	RelOptInfo *inner_rel;
+	bool		null_safe_compare = PG_NARGS() >= 6 && PG_GETARG_BOOL(5);
 
 	get_join_variables(root, args, sjinfo,
 					   &vardata1, &vardata2, &join_is_reversed);
@@ -2495,7 +2507,13 @@ eqjoinsel(PG_FUNCTION_ARGS)
 								  have_mcvs1, have_mcvs2,
 								  hasmatch1, hasmatch2,
 								  &nmatches);
-
+	/* NULL/NULL pairs contribute independently of the non-NULL estimate. */
+	if (null_safe_compare &&
+		stats1 && stats1->stanullfrac > 0.0 &&
+		stats2 && stats2->stanullfrac > 0.0)
+	{
+		selec_inner += stats1->stanullfrac * stats2->stanullfrac;
+	}
 	switch (sjinfo->jointype)
 	{
 		case JOIN_INNER:
@@ -2541,6 +2559,37 @@ eqjoinsel(PG_FUNCTION_ARGS)
 									   &nmatches,
 									   inner_rel);
 
+			if (null_safe_compare)
+			{
+				VariableStatData *inner_vardata = join_is_reversed ? &vardata1 : &vardata2;
+				Form_pg_statistic outer_stats = join_is_reversed ? stats2 : stats1;
+				Form_pg_statistic inner_stats = join_is_reversed ? stats1 : stats2;
+				double		outer_nullfrac = outer_stats ? outer_stats->stanullfrac : 0.0;
+				double		inner_nullfrac = inner_stats ? inner_stats->stanullfrac : 0.0;
+				double		inner_rows = inner_rel->rows;
+
+				if (inner_vardata->rel)
+					inner_rows = Min(inner_rows, inner_vardata->rel->rows);
+
+				if (IS_DUMMY_REL(inner_rel) ||
+					(inner_vardata->rel && IS_DUMMY_REL(inner_vardata->rel)))
+					selec = 0.0;
+				else
+				{
+					/* All-NULL inner data cannot match non-NULL outer rows. */
+					if (inner_nullfrac >= 1.0)
+						selec = 0.0;
+
+					/*
+					 * SEMI/ANTI need the fraction of outer NULLs with at
+					 * least one inner NULL, rather than the NULL/NULL pair
+					 * frequency. Scale down if fewer than one inner NULL is
+					 * expected.
+					 */
+					selec += outer_nullfrac * Min(inner_nullfrac * inner_rows, 1.0);
+				}
+			}
+
 			/*
 			 * We should never estimate the output of a semijoin to be more
 			 * rows than we estimate for an inner join with the same input
@@ -2636,6 +2685,7 @@ eqjoinsel_inner(FmgrInfo *eqproc, Oid collation,
 							   sslot1, sslot2,
 							   sslot1->nvalues, sslot2->nvalues,
 							   hasmatch1, hasmatch2,
+							   NULL, NULL,
 							   p_nmatches, &matchprodfreq);
 		nmatches = *p_nmatches;
 		CLAMP_PROBABILITY(matchprodfreq);
@@ -2845,6 +2895,7 @@ eqjoinsel_semi(FmgrInfo *eqproc, Oid collation,
 								   sslot1, sslot2,
 								   sslot1->nvalues, clamped_nvalues2,
 								   hasmatch1, hasmatch2,
+								   NULL, NULL,
 								   p_nmatches, &matchprodfreq);
 		}
 		nmatches = *p_nmatches;
@@ -2911,7 +2962,9 @@ eqjoinsel_semi(FmgrInfo *eqproc, Oid collation,
 }
 
 /*
- * Identify matching MCVs for eqjoinsel_inner or eqjoinsel_semi.
+ * Identify equal non-NULL MCVs for the equality and DISTINCT join estimators.
+ * NULL and residual values are handled by the callers; the slots and their
+ * frequencies are not modified here.
  *
  * Inputs:
  *	eqproc: FmgrInfo for equality function to use (might be reversed)
@@ -2925,6 +2978,9 @@ eqjoinsel_semi(FmgrInfo *eqproc, Oid collation,
  * Outputs:
  *	hasmatch1[], hasmatch2[]: pre-zeroed arrays of lengths nvalues1, nvalues2;
  *		entries are set to true if that MCV has a match on the other side
+ *	matchindex1[], matchindex2[]: optional arrays of the same lengths;
+ *		initialized here to -1, then set to the opposite list's zero-based
+ *		index for each match: matchindex1[i] = j and matchindex2[j] = i
  *	*p_nmatches: receives number of MCV pairs that match
  *	*p_matchprodfreq: receives sum(sslot1->numbers[i] * sslot2->numbers[j])
  *		for matching MCVs
@@ -2944,12 +3000,20 @@ eqjoinsel_find_matches(FmgrInfo *eqproc, Oid collation,
 					   AttStatsSlot *sslot1, AttStatsSlot *sslot2,
 					   int nvalues1, int nvalues2,
 					   bool *hasmatch1, bool *hasmatch2,
+					   int *matchindex1, int *matchindex2,
 					   int *p_nmatches, double *p_matchprodfreq)
 {
 	LOCAL_FCINFO(fcinfo, 2);
 	double		matchprodfreq = 0.0;
 	int			nmatches = 0;
 
+	if (matchindex1)
+		for (int i = 0; i < nvalues1; i++)
+			matchindex1[i] = -1;
+	if (matchindex2)
+		for (int j = 0; j < nvalues2; j++)
+			matchindex2[j] = -1;
+
 	/*
 	 * Save a few cycles by setting up the fcinfo struct just once.  Using
 	 * FunctionCallInvoke directly also avoids failure if the eqproc returns
@@ -2971,11 +3035,13 @@ eqjoinsel_find_matches(FmgrInfo *eqproc, Oid collation,
 		AttStatsSlot *statsHash;
 		bool	   *hasMatchProbe;
 		bool	   *hasMatchHash;
+		int		   *matchindexProbe;
+		int		   *matchindexHash;
 		int			nvaluesProbe;
 		int			nvaluesHash;
 
 		/* Make sure we build the hash table on the smaller array. */
-		if (sslot1->nvalues >= sslot2->nvalues)
+		if (nvalues1 >= nvalues2)
 		{
 			statsProbe = sslot1;
 			statsHash = sslot2;
@@ -2983,6 +3049,8 @@ eqjoinsel_find_matches(FmgrInfo *eqproc, Oid collation,
 			hasMatchHash = hasmatch2;
 			nvaluesProbe = nvalues1;
 			nvaluesHash = nvalues2;
+			matchindexProbe = matchindex1;
+			matchindexHash = matchindex2;
 		}
 		else
 		{
@@ -2994,6 +3062,8 @@ eqjoinsel_find_matches(FmgrInfo *eqproc, Oid collation,
 			hasMatchHash = hasmatch1;
 			nvaluesProbe = nvalues2;
 			nvaluesHash = nvalues1;
+			matchindexProbe = matchindex2;
+			matchindexHash = matchindex1;
 		}
 
 		/*
@@ -3063,6 +3133,10 @@ eqjoinsel_find_matches(FmgrInfo *eqproc, Oid collation,
 			if (entry != NULL && !hasMatchHash[entry->index])
 			{
 				hasMatchHash[entry->index] = hasMatchProbe[i] = true;
+				if (matchindexHash)
+					matchindexHash[entry->index] = i;
+				if (matchindexProbe)
+					matchindexProbe[i] = entry->index;
 				nmatches++;
 				matchprodfreq += statsHash->numbers[entry->index] * statsProbe->numbers[i];
 			}
@@ -3104,6 +3178,10 @@ eqjoinsel_find_matches(FmgrInfo *eqproc, Oid collation,
 				if (!fcinfo->isnull && DatumGetBool(fresult))
 				{
 					hasmatch1[i] = hasmatch2[j] = true;
+					if (matchindex1)
+						matchindex1[i] = j;
+					if (matchindex2)
+						matchindex2[j] = i;
 					matchprodfreq += sslot1->numbers[i] * sslot2->numbers[j];
 					nmatches++;
 					break;
@@ -3177,8 +3255,333 @@ mcvs_equal(MCVHashTable_hash *tab, Datum key0, Datum key1)
 	}
 }
 
+/*
+ * distinctjoinsel_semi_internal --- estimate inequality existence.
+ *
+ * Input 1 is the outer side and input 2 is the inner side.  eqproc and the hash
+ * functions retain the original operator's argument order; op_is_reversed has
+ * the same meaning as in eqjoinsel_find_matches.
+ *
+ * Equality match indices identify the inner MCV that cannot satisfy the
+ * inequality for a given outer MCV.  Any other inner MCV is a partner.
+ * IS DISTINCT FROM also treats NULL as a comparable value; ordinary "<>"
+ * never matches NULL.  The slots and their frequencies are unchanged.
+ *
+ * ANTI joins use this same matching fraction; costsize.c takes its complement.
+ */
+static double
+distinctjoinsel_semi_internal(FmgrInfo *eqproc, Oid collation,
+							  Oid hashLeft, Oid hashRight,
+							  bool op_is_reversed,
+							  VariableStatData *vardata2,
+							  double nd1, double nd2,
+							  bool isdefault1, bool isdefault2,
+							  AttStatsSlot *sslot1, AttStatsSlot *sslot2,
+							  Form_pg_statistic stats1, Form_pg_statistic stats2,
+							  bool have_mcvs1, bool have_mcvs2,
+							  RelOptInfo *inner_rel,
+							  bool null_safe_compare)
+{
+	double		nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
+	double		nullfrac2 = stats2 ? stats2->stanullfrac : 0.0;
+	bool		null_partner = null_safe_compare && nullfrac2 > 0.0;
+	double		rhs_rows = inner_rel->rows;
+	int			nvalues1 = have_mcvs1 ? sslot1->nvalues : 0;
+	int			nvalues2 = have_mcvs2 ? sslot2->nvalues : 0;
+	int			clamped_nvalues2;
+	bool	   *hasmatch1 = NULL;
+	bool	   *hasmatch2 = NULL;
+	int		   *matchindex1 = NULL;
+	int		   *matchindex2 = NULL;
+	int			nmatches = 0;
+	double		matchprodfreq = 0.0;
+	double		sumfreq1 = 0.0;
+	double		sumfreq2 = 0.0;
+	double		otherfreq1;
+	double		otherfreq2;
+	double		othernd2;
+	double		uncertainfrac;
+	double		selec = 0.0;
+
+	if (IS_DUMMY_REL(inner_rel))
+		return 0.0;
+	if (vardata2->rel)
+	{
+		/* Subquery rels may have tuples = 0 even when they produce rows. */
+		if (IS_DUMMY_REL(vardata2->rel) ||
+			(vardata2->rel->rtekind == RTE_RELATION &&
+			 vardata2->rel->tuples == 0.0))
+			return 0.0;
+		rhs_rows = Min(rhs_rows, vardata2->rel->rows);
+	}
+	if (rhs_rows <= 0.0)
+		return 0.0;
+
+	/*
+	 * These counts exclude NULL.  get_variable_numdistinct() always returns a
+	 * positive count, so override it for known all-NULL data.
+	 */
+	if (nullfrac1 >= 1.0)
+		nd1 = 0.0;
+	if (nullfrac2 >= 1.0)
+		nd2 = 0.0;
+
+	for (int i = 0; i < nvalues1; i++)
+		sumfreq1 += sslot1->numbers[i];
+	for (int j = 0; j < nvalues2; j++)
+		sumfreq2 += sslot2->numbers[j];
+	otherfreq1 = 1.0 - nullfrac1 - sumfreq1;
+	otherfreq2 = 1.0 - nullfrac2 - sumfreq2;
+	CLAMP_PROBABILITY(otherfreq1);
+	CLAMP_PROBABILITY(otherfreq2);
+
+	if (have_mcvs1 && have_mcvs2)
+	{
+		hasmatch1 = palloc0_array(bool, nvalues1);
+		hasmatch2 = palloc0_array(bool, nvalues2);
+		matchindex1 = palloc_array(int, nvalues1);
+		matchindex2 = palloc_array(int, nvalues2);
+		eqjoinsel_find_matches(eqproc, collation,
+							   hashLeft, hashRight, op_is_reversed,
+							   sslot1, sslot2, nvalues1, nvalues2,
+							   hasmatch1, hasmatch2, matchindex1, matchindex2,
+							   &nmatches, &matchprodfreq);
+	}
+
+	/*
+	 * Treat at most one estimated inner row as a singleton, for which pair
+	 * selectivity is also the existence probability.  Use the base
+	 * distribution without assuming which value survives filtering.  Estimate
+	 * non-NULL equality as eqjoinsel_inner does.  Ordinary "<>" subtracts
+	 * equality from the non-NULL pair frequency; IS DISTINCT FROM subtracts
+	 * equality and the NULL/NULL frequency from one.
+	 */
+	if (rhs_rows <= 1.0)
+	{
+		double		unmatchfreq1 = sumfreq1;
+		double		unmatchfreq2 = sumfreq2;
+		double		totalsel1 = matchprodfreq;
+		double		totalsel2 = matchprodfreq;
+
+		if (hasmatch1)
+			for (int i = 0; i < nvalues1; i++)
+				if (hasmatch1[i])
+					unmatchfreq1 -= sslot1->numbers[i];
+		if (hasmatch2)
+			for (int j = 0; j < nvalues2; j++)
+				if (hasmatch2[j])
+					unmatchfreq2 -= sslot2->numbers[j];
+		CLAMP_PROBABILITY(unmatchfreq1);
+		CLAMP_PROBABILITY(unmatchfreq2);
+		if (nd2 > nvalues2)
+			totalsel1 += unmatchfreq1 * otherfreq2 / (nd2 - nvalues2);
+		if (nd2 > nmatches)
+			totalsel1 += otherfreq1 * (otherfreq2 + unmatchfreq2) /
+				(nd2 - nmatches);
+		if (nd1 > nvalues1)
+			totalsel2 += unmatchfreq2 * otherfreq1 / (nd1 - nvalues1);
+		if (nd1 > nmatches)
+			totalsel2 += otherfreq2 * (otherfreq1 + unmatchfreq1) /
+				(nd1 - nmatches);
+		if (null_safe_compare)
+			selec = 1.0 - nullfrac1 * nullfrac2;
+		else
+			selec = (1.0 - nullfrac1) * (1.0 - nullfrac2);
+		selec -= Min(totalsel1, totalsel2);
+	}
+	else
+	{
+		/*
+		 * As in eqjoinsel_semi, retain the most frequent inner MCVs if the
+		 * estimated input cannot contain all distinct values.  NULL consumes
+		 * a separate category.  Match indices refer to the unchanged slots,
+		 * so checking the prefix needs no second round of comparisons. This
+		 * clamps value counts but does not adjust the base distribution for
+		 * inner restrictions.
+		 */
+		if (nd2 > Max(rhs_rows - (nullfrac2 > 0.0), 0.0))
+		{
+			nd2 = Max(rhs_rows - (nullfrac2 > 0.0), 0.0);
+			isdefault2 = false;
+		}
+		clamped_nvalues2 = Min(nvalues2, nd2);
+		othernd2 = Max(nd2 - clamped_nvalues2, 0.0);
+
+		/*
+		 * A sole unidentified value uses the complement of equality's
+		 * heuristic.
+		 */
+		uncertainfrac = (!isdefault1 && !isdefault2) ?
+			1.0 - 1.0 / Max(Max(nd1, nd2), 1.0) : 1.0 - DEFAULT_EQ_SEL;
+
+		/* One distinct partner admits the full outer MCV frequency. */
+		for (int i = 0; i < nvalues1; i++)
+		{
+			int			j = matchindex1 ? matchindex1[i] : -1;
+			bool		equal_mcv = j >= 0 && j < clamped_nvalues2;
+			double		matchfrac = 0.0;
+
+			/* Exclude the equal MCV; NULL is a partner only for DISTINCT. */
+			if (null_partner || clamped_nvalues2 > (equal_mcv ? 1 : 0))
+				matchfrac = 1.0;
+			else if (othernd2 > 0.0 && otherfreq2 > 0.0)
+			{
+				if (nd2 > 1.0)
+					matchfrac = 1.0;
+				else
+					matchfrac = uncertainfrac;
+			}
+			selec += sslot1->numbers[i] * matchfrac;
+		}
+
+		/* Only DISTINCT lets outer NULL match a non-NULL inner value. */
+		if (null_safe_compare && nd2 > 0.0)
+			selec += nullfrac1;
+
+		/* A NULL partner or two non-NULL values match every outer residual. */
+		if (null_partner || nd2 > 1.0)
+			selec += otherfreq1;
+		else if (clamped_nvalues2 == 1)
+		{
+			/*
+			 * If the sole inner value is an outer MCV, every outer residual
+			 * value differs from it.  Otherwise estimate its outer frequency
+			 * uniformly over the residual distinct values, capped at the
+			 * least frequent outer MCV when one is available.
+			 */
+			double		equalfreq = 0.0;
+
+			if (!matchindex2 || matchindex2[0] < 0)
+			{
+				equalfreq = otherfreq1 / Max(nd1 - nvalues1, 1.0);
+				if (nvalues1 > 0)
+					equalfreq = Min(equalfreq, sslot1->numbers[nvalues1 - 1]);
+			}
+			selec += otherfreq1 - equalfreq;
+		}
+		else if (othernd2 > 0.0 && otherfreq2 > 0.0)
+			selec += otherfreq1 * uncertainfrac;
+	}
+
+	if (hasmatch1)
+		pfree(hasmatch1);
+	if (hasmatch2)
+		pfree(hasmatch2);
+	if (matchindex1)
+		pfree(matchindex1);
+	if (matchindex2)
+		pfree(matchindex2);
+	CLAMP_PROBABILITY(selec);
+	return selec;
+}
+
+/*
+ * distinctjoinsel_semi --- gather statistics for inequality SEMI/ANTI joins.
+ *
+ * eqoperator is the equality negator of the original inequality operator.
+ * Use it for MCV comparisons, security checks and hash support, then pass the
+ * statistics in outer/inner order to distinctjoinsel_semi_internal.
+ * null_safe_compare selects IS DISTINCT FROM semantics; false selects "<>".
+ */
+static Datum
+distinctjoinsel_semi(PlannerInfo *root,
+					 Oid eqoperator, List *args,
+					 SpecialJoinInfo *sjinfo, Oid collation,
+					 bool null_safe_compare)
+{
+	double		selec;
+	VariableStatData vardata1;
+	VariableStatData vardata2;
+	double		nd1;
+	double		nd2;
+	bool		isdefault1;
+	bool		isdefault2;
+	Oid			opfuncoid = get_opcode(eqoperator);
+	FmgrInfo	eqproc;
+	Oid			hashLeft = InvalidOid;
+	Oid			hashRight = InvalidOid;
+	AttStatsSlot sslot1;
+	AttStatsSlot sslot2;
+	Form_pg_statistic stats1 = NULL;
+	Form_pg_statistic stats2 = NULL;
+	bool		have_mcvs1 = false;
+	bool		have_mcvs2 = false;
+	bool		join_is_reversed;
+	RelOptInfo *inner_rel;
+
+	get_join_variables(root, args, sjinfo,
+					   &vardata1, &vardata2, &join_is_reversed);
+	nd1 = get_variable_numdistinct(&vardata1, &isdefault1);
+	nd2 = get_variable_numdistinct(&vardata2, &isdefault2);
+	memset(&sslot1, 0, sizeof(sslot1));
+	memset(&sslot2, 0, sizeof(sslot2));
+	memset(&eqproc, 0, sizeof(eqproc));
+
+	if (HeapTupleIsValid(vardata1.statsTuple))
+	{
+		stats1 = (Form_pg_statistic) GETSTRUCT(vardata1.statsTuple);
+		if (statistic_proc_security_check(&vardata1, opfuncoid))
+			have_mcvs1 = get_attstatsslot(&sslot1, vardata1.statsTuple,
+										  STATISTIC_KIND_MCV, InvalidOid,
+										  ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS);
+	}
+	if (HeapTupleIsValid(vardata2.statsTuple))
+	{
+		stats2 = (Form_pg_statistic) GETSTRUCT(vardata2.statsTuple);
+		if (statistic_proc_security_check(&vardata2, opfuncoid))
+			have_mcvs2 = get_attstatsslot(&sslot2, vardata2.statsTuple,
+										  STATISTIC_KIND_MCV, InvalidOid,
+										  ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS);
+	}
+	if (have_mcvs1 && have_mcvs2)
+	{
+		fmgr_info(opfuncoid, &eqproc);
+		if (sslot1.nvalues + sslot2.nvalues >= EQJOINSEL_MCV_HASH_THRESHOLD)
+			(void) get_op_hash_functions_ext(eqoperator,
+											 exprType((Node *) linitial(args)),
+											 &hashLeft, &hashRight);
+	}
+
+	inner_rel = find_join_input_rel(root, sjinfo->min_righthand);
+	if (!join_is_reversed)
+		selec = distinctjoinsel_semi_internal(&eqproc, collation,
+											  hashLeft, hashRight, false,
+											  &vardata2, nd1, nd2,
+											  isdefault1, isdefault2,
+											  &sslot1, &sslot2, stats1, stats2,
+											  have_mcvs1, have_mcvs2, inner_rel,
+											  null_safe_compare);
+	else
+		selec = distinctjoinsel_semi_internal(&eqproc, collation,
+											  hashLeft, hashRight, true,
+											  &vardata1, nd2, nd1,
+											  isdefault2, isdefault1,
+											  &sslot2, &sslot1, stats2, stats1,
+											  have_mcvs2, have_mcvs1, inner_rel,
+											  null_safe_compare);
+
+	free_attstatsslot(&sslot1);
+	free_attstatsslot(&sslot2);
+	ReleaseVariableStats(vardata1);
+	ReleaseVariableStats(vardata2);
+	PG_RETURN_FLOAT8((float8) selec);
+}
+
 /*
  *		neqjoinsel		- Join selectivity of "!="
+ *
+ * An optional sixth boolean argument, null_safe_compare, enables
+ * IS DISTINCT FROM semantics.
+ *
+ * For inner and outer joins with an equality negator, let E be ordinary "="
+ * selectivity and n1/n2 the input NULL fractions.  Ordinary "<>" excludes all
+ * pairs containing NULL, so its selectivity is (1 - n1) * (1 - n2) - E.
+ * IS DISTINCT FROM complements eqjoinsel() with NULL matching enabled,
+ * giving 1 - E - n1 * n2.
+ *
+ * SEMI/ANTI joins use distinctjoinsel_semi() when an equality negator is
+ * available to estimate whether each outer row has any unequal inner partner.
+ * Both return the matching fraction; the caller complements it for ANTI rows.
  */
 Datum
 neqjoinsel(PG_FUNCTION_ARGS)
@@ -3190,30 +3593,26 @@ neqjoinsel(PG_FUNCTION_ARGS)
 	SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) PG_GETARG_POINTER(4);
 	Oid			collation = PG_GET_COLLATION();
 	float8		result;
+	bool		null_safe_compare = PG_NARGS() >= 6 && PG_GETARG_BOOL(5);
 
 	if (jointype == JOIN_SEMI || jointype == JOIN_ANTI)
 	{
-		/*
-		 * For semi-joins, if there is more than one distinct value in the RHS
-		 * relation then every non-null LHS row must find a row to join since
-		 * it can only be equal to one of them.  We'll assume that there is
-		 * always more than one distinct RHS value for the sake of stability,
-		 * though in theory we could have special cases for empty RHS
-		 * (selectivity = 0) and single-distinct-value RHS (selectivity =
-		 * fraction of LHS that has the same value as the single RHS value).
-		 *
-		 * For anti-joins, if we use the same assumption that there is more
-		 * than one distinct key in the RHS relation, then every non-null LHS
-		 * row must be suppressed by the anti-join.
-		 *
-		 * So either way, the selectivity estimate should be 1 - nullfrac.
-		 */
+		Oid			eqoperator = get_negator(operator);
 		VariableStatData leftvar;
 		VariableStatData rightvar;
 		bool		reversed;
 		HeapTuple	statsTuple;
 		double		nullfrac;
 
+		if (OidIsValid(eqoperator))
+			return distinctjoinsel_semi(root, eqoperator, args,
+										sjinfo, collation, null_safe_compare);
+
+		/*
+		 * Without an equality negator, retain the heuristic that every
+		 * non-NULL outer row has a partner.  SEMI and ANTI both return the
+		 * matching fraction; the caller complements it for ANTI output rows.
+		 */
 		get_join_variables(root, args, sjinfo, &leftvar, &rightvar, &reversed);
 		statsTuple = reversed ? rightvar.statsTuple : leftvar.statsTuple;
 		if (HeapTupleIsValid(statsTuple))
@@ -3228,28 +3627,51 @@ neqjoinsel(PG_FUNCTION_ARGS)
 	else
 	{
 		/*
-		 * We want 1 - eqjoinsel() where the equality operator is the one
-		 * associated with this != operator, that is, its negator.
+		 * Reuse the equality estimate for this operator's negator.  For IS
+		 * DISTINCT FROM, include NULL/NULL equality before taking the
+		 * complement.  Ordinary "<>" must also exclude pairs containing NULL.
 		 */
 		Oid			eqop = get_negator(operator);
 
 		if (eqop)
 		{
 			result =
-				DatumGetFloat8(DirectFunctionCall5Coll(eqjoinsel,
+				DatumGetFloat8(DirectFunctionCall6Coll(eqjoinsel,
 													   collation,
 													   PointerGetDatum(root),
 													   ObjectIdGetDatum(eqop),
 													   PointerGetDatum(args),
 													   Int16GetDatum(jointype),
-													   PointerGetDatum(sjinfo)));
+													   PointerGetDatum(sjinfo),
+													   BoolGetDatum(null_safe_compare)));
 		}
 		else
 		{
 			/* Use default selectivity (should we raise an error instead?) */
 			result = DEFAULT_EQ_SEL;
 		}
-		result = 1.0 - result;
+		if (null_safe_compare)
+			result = 1.0 - result;
+		else
+		{
+			VariableStatData leftvar;
+			VariableStatData rightvar;
+			bool		reversed;
+			double		nullfrac1 = 0.0;
+			double		nullfrac2 = 0.0;
+
+			get_join_variables(root, args, sjinfo, &leftvar, &rightvar,
+							   &reversed);
+			if (HeapTupleIsValid(leftvar.statsTuple))
+				nullfrac1 = ((Form_pg_statistic) GETSTRUCT(leftvar.statsTuple))->stanullfrac;
+			if (HeapTupleIsValid(rightvar.statsTuple))
+				nullfrac2 = ((Form_pg_statistic) GETSTRUCT(rightvar.statsTuple))->stanullfrac;
+			ReleaseVariableStats(leftvar);
+			ReleaseVariableStats(rightvar);
+
+			result = (1.0 - nullfrac1) * (1.0 - nullfrac2) - result;
+			CLAMP_PROBABILITY(result);
+		}
 	}
 
 	PG_RETURN_FLOAT8(result);
diff --git a/src/include/optimizer/plancat.h b/src/include/optimizer/plancat.h
index 09baf1a6..01a18464 100644
--- a/src/include/optimizer/plancat.h
+++ b/src/include/optimizer/plancat.h
@@ -51,6 +51,12 @@ extern Selectivity join_selectivity(PlannerInfo *root,
 									Oid inputcollid,
 									JoinType jointype,
 									SpecialJoinInfo *sjinfo);
+extern Selectivity nullsafe_join_selectivity(PlannerInfo *root,
+											 Oid operatorid,
+											 List *args,
+											 Oid inputcollid,
+											 JoinType jointype,
+											 SpecialJoinInfo *sjinfo);
 
 extern Selectivity function_selectivity(PlannerInfo *root,
 										Oid funcid,
diff --git a/src/test/regress/expected/join.out b/src/test/regress/expected/join.out
index 7773852e..7c70accf 100644
--- a/src/test/regress/expected/join.out
+++ b/src/test/regress/expected/join.out
@@ -10347,15 +10347,15 @@ EXPLAIN (COSTS OFF)
 SELECT * FROM
 (SELECT n2.a FROM sj n1, sj n2 WHERE n1.a <> n2.a) q0, sl
 WHERE q0.a = 1;
-          QUERY PLAN           
--------------------------------
+             QUERY PLAN              
+-------------------------------------
  Nested Loop
-   Join Filter: (n1.a <> n2.a)
    ->  Nested Loop
-         ->  Seq Scan on sl
+         Join Filter: (n1.a <> n2.a)
          ->  Seq Scan on sj n2
                Filter: (a = 1)
-   ->  Seq Scan on sj n1
+         ->  Seq Scan on sj n1
+   ->  Seq Scan on sl
 (7 rows)
 
 -- Do not forget to replace relid in bare Var join clause (bug #19435)
diff --git a/src/test/regress/expected/planner_est.out b/src/test/regress/expected/planner_est.out
index 6a8d2238..55fec599 100644
--- a/src/test/regress/expected/planner_est.out
+++ b/src/test/regress/expected/planner_est.out
@@ -224,4 +224,335 @@ EXPLAIN (COSTS OFF) SELECT * FROM char_table_1 WHERE c < 'Q';
    Filter: (c < 'Q'::"char")
 (2 rows)
 
+-- Test inequality and NULL-safe equality join estimates with NULLs and values
+-- outside the MCV lists.  SEMI/ANTI estimates measure existence of a partner.
+CREATE TEMP TABLE distinct_outer AS
+SELECT CASE WHEN g <= 20 THEN NULL WHEN g <= 80 THEN 1 ELSE 2 END AS a,
+       g AS tail, g % 40 AS many,
+       CASE WHEN g <= 20 THEN NULL ELSE g END AS nullable_tail
+FROM generate_series(1, 100) g;
+CREATE TEMP TABLE distinct_inner AS
+SELECT 1 AS one, NULL::integer AS nulls, g % 2 + 1 AS two,
+       (g % 40)::bigint AS many, g AS tail
+FROM generate_series(1, 100) g;
+ANALYZE distinct_outer;
+ANALYZE distinct_inner;
+-- Ordinary <> excludes pairs containing NULL from its equality complement.
+SELECT explain_mask_costs($$
+SELECT FROM distinct_outer x, distinct_outer y WHERE x.a <> y.a;$$,
+true, true, false, true);
+                                         explain_mask_costs                                          
+-----------------------------------------------------------------------------------------------------
+ Nested Loop  (cost=N..N rows=2400 width=N) (actual rows=2400.00 loops=1)
+   Join Filter: (x.a <> y.a)
+   Rows Removed by Join Filter: 7600
+   ->  Seq Scan on distinct_outer x  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1)
+   ->  Materialize  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=100)
+         ->  Seq Scan on distinct_outer y  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1)
+(6 rows)
+
+SELECT explain_mask_costs($$
+SELECT FROM distinct_outer x, distinct_inner y WHERE y.nulls <> x.a;$$,
+true, true, false, true);
+                                         explain_mask_costs                                          
+-----------------------------------------------------------------------------------------------------
+ Nested Loop  (cost=N..N rows=1 width=N) (actual rows=0.00 loops=1)
+   Join Filter: (y.nulls <> x.a)
+   Rows Removed by Join Filter: 10000
+   ->  Seq Scan on distinct_outer x  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1)
+   ->  Materialize  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=100)
+         ->  Seq Scan on distinct_inner y  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1)
+(6 rows)
+
+-- Count NULL/NULL pairs even when non-NULL values are outside the MCV lists.
+SELECT explain_mask_costs($$
+SELECT FROM distinct_outer x, distinct_outer y
+WHERE x.nullable_tail IS NOT DISTINCT FROM y.nullable_tail;$$,
+true, true, false, true);
+                                         explain_mask_costs                                          
+-----------------------------------------------------------------------------------------------------
+ Nested Loop  (cost=N..N rows=480 width=N) (actual rows=480.00 loops=1)
+   Join Filter: (NOT (x.nullable_tail IS DISTINCT FROM y.nullable_tail))
+   Rows Removed by Join Filter: 9520
+   ->  Seq Scan on distinct_outer x  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1)
+   ->  Materialize  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=100)
+         ->  Seq Scan on distinct_outer y  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1)
+(6 rows)
+
+SELECT explain_mask_costs($$
+SELECT FROM distinct_outer x, distinct_outer y
+WHERE x.nullable_tail IS DISTINCT FROM y.nullable_tail;$$,
+true, true, false, true);
+                                         explain_mask_costs                                          
+-----------------------------------------------------------------------------------------------------
+ Nested Loop  (cost=N..N rows=9520 width=N) (actual rows=9520.00 loops=1)
+   Join Filter: (x.nullable_tail IS DISTINCT FROM y.nullable_tail)
+   Rows Removed by Join Filter: 480
+   ->  Seq Scan on distinct_outer x  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1)
+   ->  Materialize  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=100)
+         ->  Seq Scan on distinct_outer y  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1)
+(6 rows)
+
+-- NULL matches must not suppress non-MCV matches in a NULL-safe SEMI join.
+SELECT explain_mask_costs($$
+SELECT x.nullable_tail FROM distinct_outer x WHERE EXISTS
+  (SELECT FROM distinct_outer y
+   WHERE x.nullable_tail IS NOT DISTINCT FROM y.nullable_tail);$$,
+true, true, false, true);
+                                         explain_mask_costs                                          
+-----------------------------------------------------------------------------------------------------
+ Nested Loop Semi Join  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1)
+   Join Filter: (NOT (x.nullable_tail IS DISTINCT FROM y.nullable_tail))
+   Rows Removed by Join Filter: 4760
+   ->  Seq Scan on distinct_outer x  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1)
+   ->  Materialize  (cost=N..N rows=100 width=N) (actual rows=48.60 loops=100)
+         ->  Seq Scan on distinct_outer y  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1)
+(6 rows)
+
+-- Outer NULLs have no NULL-safe equality partner in a non-NULL inner column.
+SELECT explain_mask_costs($$
+SELECT x.nullable_tail FROM distinct_outer x WHERE NOT EXISTS
+  (SELECT FROM distinct_inner y
+   WHERE x.nullable_tail IS NOT DISTINCT FROM y.tail);$$,
+true, true, false, true);
+                                         explain_mask_costs                                          
+-----------------------------------------------------------------------------------------------------
+ Nested Loop Anti Join  (cost=N..N rows=20 width=N) (actual rows=20.00 loops=1)
+   Join Filter: (NOT (x.nullable_tail IS DISTINCT FROM y.tail))
+   Rows Removed by Join Filter: 6760
+   ->  Seq Scan on distinct_outer x  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1)
+   ->  Materialize  (cost=N..N rows=100 width=N) (actual rows=68.40 loops=100)
+         ->  Seq Scan on distinct_inner y  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1)
+(6 rows)
+
+-- All-NULL inner data matches only the outer NULLs, even without MCV lists.
+SELECT explain_mask_costs($$
+SELECT x.nullable_tail FROM distinct_outer x WHERE EXISTS
+  (SELECT FROM distinct_inner y
+   WHERE x.nullable_tail IS NOT DISTINCT FROM y.nulls);$$,
+true, true, false, true);
+                                         explain_mask_costs                                          
+-----------------------------------------------------------------------------------------------------
+ Nested Loop Semi Join  (cost=N..N rows=20 width=N) (actual rows=20.00 loops=1)
+   Join Filter: (NOT (x.nullable_tail IS DISTINCT FROM y.nulls))
+   Rows Removed by Join Filter: 8000
+   ->  Seq Scan on distinct_outer x  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1)
+   ->  Materialize  (cost=N..N rows=100 width=N) (actual rows=80.20 loops=100)
+         ->  Seq Scan on distinct_inner y  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1)
+(6 rows)
+
+-- A sole inner value gives SEMI unequal outer rows and ANTI equal outer rows.
+SELECT explain_mask_costs($$
+SELECT x.a FROM distinct_outer x WHERE EXISTS
+  (SELECT FROM distinct_inner y WHERE x.a IS DISTINCT FROM y.one);$$,
+true, true, false, true);
+                                         explain_mask_costs                                          
+-----------------------------------------------------------------------------------------------------
+ Nested Loop Semi Join  (cost=N..N rows=40 width=N) (actual rows=40.00 loops=1)
+   Join Filter: (x.a IS DISTINCT FROM y.one)
+   Rows Removed by Join Filter: 6000
+   ->  Seq Scan on distinct_outer x  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1)
+   ->  Materialize  (cost=N..N rows=100 width=N) (actual rows=60.40 loops=100)
+         ->  Seq Scan on distinct_inner y  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1)
+(6 rows)
+
+SELECT explain_mask_costs($$
+SELECT x.a FROM distinct_outer x WHERE NOT EXISTS
+  (SELECT FROM distinct_inner y WHERE y.one IS DISTINCT FROM x.a);$$,
+true, true, false, true);
+                                         explain_mask_costs                                          
+-----------------------------------------------------------------------------------------------------
+ Nested Loop Anti Join  (cost=N..N rows=60 width=N) (actual rows=60.00 loops=1)
+   Join Filter: (y.one IS DISTINCT FROM x.a)
+   Rows Removed by Join Filter: 6000
+   ->  Seq Scan on distinct_outer x  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1)
+   ->  Materialize  (cost=N..N rows=100 width=N) (actual rows=60.40 loops=100)
+         ->  Seq Scan on distinct_inner y  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1)
+(6 rows)
+
+-- With an all-NULL inner input, DISTINCT ANTI keeps only outer NULLs.
+SELECT explain_mask_costs($$
+SELECT x.a FROM distinct_outer x WHERE NOT EXISTS
+  (SELECT FROM distinct_inner y WHERE x.a IS DISTINCT FROM y.nulls);$$,
+true, true, false, true);
+                                         explain_mask_costs                                          
+-----------------------------------------------------------------------------------------------------
+ Nested Loop Anti Join  (cost=N..N rows=20 width=N) (actual rows=20.00 loops=1)
+   Join Filter: (x.a IS DISTINCT FROM y.nulls)
+   Rows Removed by Join Filter: 2000
+   ->  Seq Scan on distinct_outer x  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1)
+   ->  Materialize  (cost=N..N rows=100 width=N) (actual rows=20.80 loops=100)
+         ->  Seq Scan on distinct_inner y  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1)
+(6 rows)
+
+-- Two different inner values provide a DISTINCT partner for every outer row.
+-- Zero output rows are estimated as one because of clamp_row_est().
+SELECT explain_mask_costs($$
+SELECT x.a FROM distinct_outer x WHERE NOT EXISTS
+  (SELECT FROM distinct_inner y WHERE x.a IS DISTINCT FROM y.two);$$,
+true, true, false, true);
+                                        explain_mask_costs                                         
+---------------------------------------------------------------------------------------------------
+ Nested Loop Anti Join  (cost=N..N rows=1 width=N) (actual rows=0.00 loops=1)
+   Join Filter: (x.a IS DISTINCT FROM y.two)
+   Rows Removed by Join Filter: 20
+   ->  Seq Scan on distinct_outer x  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1)
+   ->  Materialize  (cost=N..N rows=100 width=N) (actual rows=1.20 loops=100)
+         ->  Seq Scan on distinct_inner y  (cost=N..N rows=100 width=N) (actual rows=2.00 loops=1)
+(6 rows)
+
+-- All outer values are outside the MCV list; one equals the sole inner value.
+SELECT explain_mask_costs($$
+SELECT x.tail FROM distinct_outer x WHERE EXISTS
+  (SELECT FROM distinct_inner y WHERE x.tail IS DISTINCT FROM y.one);$$,
+true, true, false, true);
+                                         explain_mask_costs                                          
+-----------------------------------------------------------------------------------------------------
+ Nested Loop Semi Join  (cost=N..N rows=99 width=N) (actual rows=99.00 loops=1)
+   Join Filter: (x.tail IS DISTINCT FROM y.one)
+   Rows Removed by Join Filter: 100
+   ->  Seq Scan on distinct_outer x  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1)
+   ->  Materialize  (cost=N..N rows=100 width=N) (actual rows=1.99 loops=100)
+         ->  Seq Scan on distinct_inner y  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1)
+(6 rows)
+
+-- Cross-type MCV lists exercise reversed operands and hashing in assertion builds.
+SELECT explain_mask_costs($$
+SELECT x.many FROM distinct_outer x WHERE NOT EXISTS
+  (SELECT FROM distinct_inner y WHERE y.many IS DISTINCT FROM x.many);$$,
+true, true, false, true);
+                                        explain_mask_costs                                         
+---------------------------------------------------------------------------------------------------
+ Nested Loop Anti Join  (cost=N..N rows=1 width=N) (actual rows=0.00 loops=1)
+   Join Filter: (y.many IS DISTINCT FROM x.many)
+   Rows Removed by Join Filter: 3
+   ->  Seq Scan on distinct_outer x  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1)
+   ->  Materialize  (cost=N..N rows=100 width=N) (actual rows=1.03 loops=100)
+         ->  Seq Scan on distinct_inner y  (cost=N..N rows=100 width=N) (actual rows=2.00 loops=1)
+(6 rows)
+
+-- Ordinary <> uses the same existence estimate but cannot match either NULL.
+-- A sole inner value matches only unequal non-NULL outer rows.
+SELECT explain_mask_costs($$
+SELECT x.a FROM distinct_outer x WHERE EXISTS
+  (SELECT FROM distinct_inner y WHERE x.a <> y.one);$$,
+true, true, false, true);
+                                         explain_mask_costs                                          
+-----------------------------------------------------------------------------------------------------
+ Nested Loop Semi Join  (cost=N..N rows=20 width=N) (actual rows=20.00 loops=1)
+   Join Filter: (x.a <> y.one)
+   Rows Removed by Join Filter: 8000
+   ->  Seq Scan on distinct_outer x  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1)
+   ->  Materialize  (cost=N..N rows=100 width=N) (actual rows=80.20 loops=100)
+         ->  Seq Scan on distinct_inner y  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1)
+(6 rows)
+
+-- An all-NULL inner input has no <> partners, so ANTI keeps all outer rows.
+SELECT explain_mask_costs($$
+SELECT x.a FROM distinct_outer x WHERE NOT EXISTS
+  (SELECT FROM distinct_inner y WHERE x.a <> y.nulls);$$,
+true, true, false, true);
+                                         explain_mask_costs                                          
+-----------------------------------------------------------------------------------------------------
+ Nested Loop Anti Join  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1)
+   Join Filter: (x.a <> y.nulls)
+   Rows Removed by Join Filter: 10000
+   ->  Seq Scan on distinct_outer x  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1)
+   ->  Materialize  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=100)
+         ->  Seq Scan on distinct_inner y  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1)
+(6 rows)
+
+-- Two non-NULL inner values match every non-NULL outer row, leaving NULLs to ANTI.
+SELECT explain_mask_costs($$
+SELECT x.a FROM distinct_outer x WHERE NOT EXISTS
+  (SELECT FROM distinct_inner y WHERE x.a <> y.two);$$,
+true, true, false, true);
+                                         explain_mask_costs                                          
+-----------------------------------------------------------------------------------------------------
+ Nested Loop Anti Join  (cost=N..N rows=20 width=N) (actual rows=20.00 loops=1)
+   Join Filter: (x.a <> y.two)
+   Rows Removed by Join Filter: 2020
+   ->  Seq Scan on distinct_outer x  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1)
+   ->  Materialize  (cost=N..N rows=100 width=N) (actual rows=21.00 loops=100)
+         ->  Seq Scan on distinct_inner y  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1)
+(6 rows)
+
+-- With one inner row, use the non-NULL pair frequency minus equality.
+SELECT explain_mask_costs($$
+SELECT x.a FROM distinct_outer x WHERE EXISTS
+  (SELECT FROM (SELECT one FROM distinct_inner LIMIT 1) y WHERE x.a <> y.one);$$,
+true, true, false, true);
+                                          explain_mask_costs                                           
+-------------------------------------------------------------------------------------------------------
+ Nested Loop Semi Join  (cost=N..N rows=20 width=N) (actual rows=20.00 loops=1)
+   Join Filter: (x.a <> distinct_inner.one)
+   Rows Removed by Join Filter: 80
+   ->  Seq Scan on distinct_outer x  (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1)
+   ->  Materialize  (cost=N..N rows=1 width=N) (actual rows=1.00 loops=100)
+         ->  Limit  (cost=N..N rows=1 width=N) (actual rows=1.00 loops=1)
+               ->  Seq Scan on distinct_inner  (cost=N..N rows=100 width=N) (actual rows=1.00 loops=1)
+(7 rows)
+
+-- Unrecognized estimators keep their five-argument API and legacy estimates.
+-- Both operators may use the same estimator, as some extensions do.
+CREATE SCHEMA distinct_est;
+CREATE OPERATOR distinct_est.= (
+  LEFTARG = integer, RIGHTARG = integer,
+  FUNCTION = pg_catalog.int4eq, NEGATOR = OPERATOR(distinct_est.<>),
+  JOIN = pg_catalog.contjoinsel);
+CREATE OPERATOR distinct_est.<> (
+  LEFTARG = integer, RIGHTARG = integer,
+  FUNCTION = pg_catalog.int4ne, NEGATOR = OPERATOR(distinct_est.=),
+  JOIN = pg_catalog.contjoinsel);
+SET search_path = distinct_est, public, pg_catalog;
+SELECT explain_mask_costs($$
+SELECT FROM distinct_outer x, distinct_inner y
+WHERE x.tail IS DISTINCT FROM y.tail;$$,
+false, true, false, true);
+                           explain_mask_costs                           
+------------------------------------------------------------------------
+ Nested Loop  (cost=N..N rows=9990 width=N)
+   Join Filter: (x.tail IS DISTINCT FROM y.tail)
+   ->  Seq Scan on distinct_outer x  (cost=N..N rows=100 width=N)
+   ->  Materialize  (cost=N..N rows=100 width=N)
+         ->  Seq Scan on distinct_inner y  (cost=N..N rows=100 width=N)
+(5 rows)
+
+SELECT explain_mask_costs($$
+SELECT FROM distinct_outer x, distinct_inner y
+WHERE x.tail IS NOT DISTINCT FROM y.tail;$$,
+false, true, false, true);
+                           explain_mask_costs                           
+------------------------------------------------------------------------
+ Nested Loop  (cost=N..N rows=10 width=N)
+   Join Filter: (NOT (x.tail IS DISTINCT FROM y.tail))
+   ->  Seq Scan on distinct_outer x  (cost=N..N rows=100 width=N)
+   ->  Materialize  (cost=N..N rows=100 width=N)
+         ->  Seq Scan on distinct_inner y  (cost=N..N rows=100 width=N)
+(5 rows)
+
+-- An alias of eqjoinsel is still a separate, five-argument catalog procedure.
+CREATE FUNCTION distinct_est.join_est(internal, oid, internal, smallint, internal)
+  RETURNS double precision AS 'eqjoinsel' LANGUAGE internal STRICT;
+ALTER OPERATOR distinct_est.= (integer, integer)
+  SET (JOIN = distinct_est.join_est);
+SELECT explain_mask_costs($$
+SELECT FROM distinct_outer x, distinct_outer y
+WHERE x.a IS NOT DISTINCT FROM y.a;$$,
+false, true, false, true);
+                           explain_mask_costs                           
+------------------------------------------------------------------------
+ Nested Loop  (cost=N..N rows=4000 width=N)
+   Join Filter: (NOT (x.a IS DISTINCT FROM y.a))
+   ->  Seq Scan on distinct_outer x  (cost=N..N rows=100 width=N)
+   ->  Materialize  (cost=N..N rows=100 width=N)
+         ->  Seq Scan on distinct_outer y  (cost=N..N rows=100 width=N)
+(5 rows)
+
+RESET search_path;
+DROP OPERATOR distinct_est.= (integer, integer);
+DROP OPERATOR distinct_est.<> (integer, integer);
+DROP FUNCTION distinct_est.join_est(internal, oid, internal, smallint, internal);
+DROP SCHEMA distinct_est;
+DROP TABLE distinct_outer, distinct_inner;
 DROP FUNCTION explain_mask_costs(text, bool, bool, bool, bool);
diff --git a/src/test/regress/sql/planner_est.sql b/src/test/regress/sql/planner_est.sql
index 1da208ec..f3d28e03 100644
--- a/src/test/regress/sql/planner_est.sql
+++ b/src/test/regress/sql/planner_est.sql
@@ -156,4 +156,155 @@ CREATE TEMP TABLE char_table_1 AS
 ANALYZE char_table_1;
 EXPLAIN (COSTS OFF) SELECT * FROM char_table_1 WHERE c < 'Q';
 
+-- Test inequality and NULL-safe equality join estimates with NULLs and values
+-- outside the MCV lists.  SEMI/ANTI estimates measure existence of a partner.
+CREATE TEMP TABLE distinct_outer AS
+SELECT CASE WHEN g <= 20 THEN NULL WHEN g <= 80 THEN 1 ELSE 2 END AS a,
+       g AS tail, g % 40 AS many,
+       CASE WHEN g <= 20 THEN NULL ELSE g END AS nullable_tail
+FROM generate_series(1, 100) g;
+CREATE TEMP TABLE distinct_inner AS
+SELECT 1 AS one, NULL::integer AS nulls, g % 2 + 1 AS two,
+       (g % 40)::bigint AS many, g AS tail
+FROM generate_series(1, 100) g;
+ANALYZE distinct_outer;
+ANALYZE distinct_inner;
+
+-- Ordinary <> excludes pairs containing NULL from its equality complement.
+SELECT explain_mask_costs($$
+SELECT FROM distinct_outer x, distinct_outer y WHERE x.a <> y.a;$$,
+true, true, false, true);
+SELECT explain_mask_costs($$
+SELECT FROM distinct_outer x, distinct_inner y WHERE y.nulls <> x.a;$$,
+true, true, false, true);
+
+-- Count NULL/NULL pairs even when non-NULL values are outside the MCV lists.
+SELECT explain_mask_costs($$
+SELECT FROM distinct_outer x, distinct_outer y
+WHERE x.nullable_tail IS NOT DISTINCT FROM y.nullable_tail;$$,
+true, true, false, true);
+SELECT explain_mask_costs($$
+SELECT FROM distinct_outer x, distinct_outer y
+WHERE x.nullable_tail IS DISTINCT FROM y.nullable_tail;$$,
+true, true, false, true);
+
+-- NULL matches must not suppress non-MCV matches in a NULL-safe SEMI join.
+SELECT explain_mask_costs($$
+SELECT x.nullable_tail FROM distinct_outer x WHERE EXISTS
+  (SELECT FROM distinct_outer y
+   WHERE x.nullable_tail IS NOT DISTINCT FROM y.nullable_tail);$$,
+true, true, false, true);
+
+-- Outer NULLs have no NULL-safe equality partner in a non-NULL inner column.
+SELECT explain_mask_costs($$
+SELECT x.nullable_tail FROM distinct_outer x WHERE NOT EXISTS
+  (SELECT FROM distinct_inner y
+   WHERE x.nullable_tail IS NOT DISTINCT FROM y.tail);$$,
+true, true, false, true);
+
+-- All-NULL inner data matches only the outer NULLs, even without MCV lists.
+SELECT explain_mask_costs($$
+SELECT x.nullable_tail FROM distinct_outer x WHERE EXISTS
+  (SELECT FROM distinct_inner y
+   WHERE x.nullable_tail IS NOT DISTINCT FROM y.nulls);$$,
+true, true, false, true);
+
+-- A sole inner value gives SEMI unequal outer rows and ANTI equal outer rows.
+SELECT explain_mask_costs($$
+SELECT x.a FROM distinct_outer x WHERE EXISTS
+  (SELECT FROM distinct_inner y WHERE x.a IS DISTINCT FROM y.one);$$,
+true, true, false, true);
+SELECT explain_mask_costs($$
+SELECT x.a FROM distinct_outer x WHERE NOT EXISTS
+  (SELECT FROM distinct_inner y WHERE y.one IS DISTINCT FROM x.a);$$,
+true, true, false, true);
+
+-- With an all-NULL inner input, DISTINCT ANTI keeps only outer NULLs.
+SELECT explain_mask_costs($$
+SELECT x.a FROM distinct_outer x WHERE NOT EXISTS
+  (SELECT FROM distinct_inner y WHERE x.a IS DISTINCT FROM y.nulls);$$,
+true, true, false, true);
+
+-- Two different inner values provide a DISTINCT partner for every outer row.
+-- Zero output rows are estimated as one because of clamp_row_est().
+SELECT explain_mask_costs($$
+SELECT x.a FROM distinct_outer x WHERE NOT EXISTS
+  (SELECT FROM distinct_inner y WHERE x.a IS DISTINCT FROM y.two);$$,
+true, true, false, true);
+
+-- All outer values are outside the MCV list; one equals the sole inner value.
+SELECT explain_mask_costs($$
+SELECT x.tail FROM distinct_outer x WHERE EXISTS
+  (SELECT FROM distinct_inner y WHERE x.tail IS DISTINCT FROM y.one);$$,
+true, true, false, true);
+
+-- Cross-type MCV lists exercise reversed operands and hashing in assertion builds.
+SELECT explain_mask_costs($$
+SELECT x.many FROM distinct_outer x WHERE NOT EXISTS
+  (SELECT FROM distinct_inner y WHERE y.many IS DISTINCT FROM x.many);$$,
+true, true, false, true);
+
+-- Ordinary <> uses the same existence estimate but cannot match either NULL.
+-- A sole inner value matches only unequal non-NULL outer rows.
+SELECT explain_mask_costs($$
+SELECT x.a FROM distinct_outer x WHERE EXISTS
+  (SELECT FROM distinct_inner y WHERE x.a <> y.one);$$,
+true, true, false, true);
+
+-- An all-NULL inner input has no <> partners, so ANTI keeps all outer rows.
+SELECT explain_mask_costs($$
+SELECT x.a FROM distinct_outer x WHERE NOT EXISTS
+  (SELECT FROM distinct_inner y WHERE x.a <> y.nulls);$$,
+true, true, false, true);
+
+-- Two non-NULL inner values match every non-NULL outer row, leaving NULLs to ANTI.
+SELECT explain_mask_costs($$
+SELECT x.a FROM distinct_outer x WHERE NOT EXISTS
+  (SELECT FROM distinct_inner y WHERE x.a <> y.two);$$,
+true, true, false, true);
+
+-- With one inner row, use the non-NULL pair frequency minus equality.
+SELECT explain_mask_costs($$
+SELECT x.a FROM distinct_outer x WHERE EXISTS
+  (SELECT FROM (SELECT one FROM distinct_inner LIMIT 1) y WHERE x.a <> y.one);$$,
+true, true, false, true);
+
+-- Unrecognized estimators keep their five-argument API and legacy estimates.
+-- Both operators may use the same estimator, as some extensions do.
+CREATE SCHEMA distinct_est;
+CREATE OPERATOR distinct_est.= (
+  LEFTARG = integer, RIGHTARG = integer,
+  FUNCTION = pg_catalog.int4eq, NEGATOR = OPERATOR(distinct_est.<>),
+  JOIN = pg_catalog.contjoinsel);
+CREATE OPERATOR distinct_est.<> (
+  LEFTARG = integer, RIGHTARG = integer,
+  FUNCTION = pg_catalog.int4ne, NEGATOR = OPERATOR(distinct_est.=),
+  JOIN = pg_catalog.contjoinsel);
+SET search_path = distinct_est, public, pg_catalog;
+SELECT explain_mask_costs($$
+SELECT FROM distinct_outer x, distinct_inner y
+WHERE x.tail IS DISTINCT FROM y.tail;$$,
+false, true, false, true);
+SELECT explain_mask_costs($$
+SELECT FROM distinct_outer x, distinct_inner y
+WHERE x.tail IS NOT DISTINCT FROM y.tail;$$,
+false, true, false, true);
+
+-- An alias of eqjoinsel is still a separate, five-argument catalog procedure.
+CREATE FUNCTION distinct_est.join_est(internal, oid, internal, smallint, internal)
+  RETURNS double precision AS 'eqjoinsel' LANGUAGE internal STRICT;
+ALTER OPERATOR distinct_est.= (integer, integer)
+  SET (JOIN = distinct_est.join_est);
+SELECT explain_mask_costs($$
+SELECT FROM distinct_outer x, distinct_outer y
+WHERE x.a IS NOT DISTINCT FROM y.a;$$,
+false, true, false, true);
+RESET search_path;
+DROP OPERATOR distinct_est.= (integer, integer);
+DROP OPERATOR distinct_est.<> (integer, integer);
+DROP FUNCTION distinct_est.join_est(internal, oid, internal, smallint, internal);
+DROP SCHEMA distinct_est;
+
+DROP TABLE distinct_outer, distinct_inner;
+
 DROP FUNCTION explain_mask_costs(text, bool, bool, bool, bool);

base-commit: 1d657c6e013e152ed37b42a22ee9f291179ee50f
-- 
2.43.0

