diff --git a/src/backend/commands/discard.c b/src/backend/commands/discard.c
index 57d3d7dd9b..3fc5106529 100644
--- a/src/backend/commands/discard.c
+++ b/src/backend/commands/discard.c
@@ -19,6 +19,7 @@
 #include "commands/discard.h"
 #include "commands/prepare.h"
 #include "commands/sequence.h"
+#include "commands/trigger.h"
 #include "utils/guc.h"
 #include "utils/portal.h"
 
@@ -73,6 +74,7 @@ DiscardAll(bool isTopLevel)
 	Async_UnlistenAll();
 	LockReleaseAll(USER_LOCKMETHOD, true);
 	ResetPlanCache();
+	RI_DropAllPreparedPlan();
 	ResetTempTableNamespace();
 	ResetSequenceCaches();
 }
diff --git a/src/backend/utils/adt/ri_triggers.c b/src/backend/utils/adt/ri_triggers.c
index 6e3a41062f..bf61a27ca3 100644
--- a/src/backend/utils/adt/ri_triggers.c
+++ b/src/backend/utils/adt/ri_triggers.c
@@ -2646,7 +2646,6 @@ ri_HashPreparedPlan(RI_QueryKey *key, SPIPlanPtr plan)
 	entry->plan = plan;
 }
 
-
 /*
  * ri_KeysEqual -
  *
@@ -2887,3 +2886,30 @@ RI_FKey_trigger_type(Oid tgfoid)
 
 	return RI_TRIGGER_NONE;
 }
+
+/*
+ * RI_DropAllPreparedPlan -
+ *
+ * Delete all plans from our private SPI query plan hashtable.
+ */
+void
+RI_DropAllPreparedPlan(void)
+{
+	HASH_SEQ_STATUS seq;
+	RI_QueryHashEntry *entry;
+
+	/* nothing cached */
+	if(!ri_query_cache)
+		return;
+
+	/* walk over cache */
+	hash_seq_init(&seq, ri_query_cache);
+	while((entry = hash_seq_search(&seq)) != NULL)
+	{
+		/* Relase the plancache entry */
+		SPI_freeplan(entry->plan);
+
+		/* Now we can remove the hash table entry */
+		hash_search(ri_query_cache, &entry->key, HASH_REMOVE, NULL);
+	}
+}
diff --git a/src/include/commands/trigger.h b/src/include/commands/trigger.h
index 9e557cfbce..b33bb31963 100644
--- a/src/include/commands/trigger.h
+++ b/src/include/commands/trigger.h
@@ -250,6 +250,7 @@ extern bool AfterTriggerPendingOnRel(Oid relid);
 /*
  * in utils/adt/ri_triggers.c
  */
+extern void RI_DropAllPreparedPlan(void);
 extern bool RI_FKey_pk_upd_check_required(Trigger *trigger, Relation pk_rel,
 										  TupleTableSlot *old_slot, TupleTableSlot *new_slot);
 extern bool RI_FKey_fk_upd_check_required(Trigger *trigger, Relation fk_rel,
