diff --git a/src/backend/utils/cache/typcache.c b/src/backend/utils/cache/typcache.c
index f51248b70d..0fcb150355 100644
--- a/src/backend/utils/cache/typcache.c
+++ b/src/backend/utils/cache/typcache.c
@@ -1832,6 +1832,7 @@ assign_record_type_typmod(TupleDesc tupDesc)
 	RecordCacheEntry *recentry;
 	TupleDesc	entDesc;
 	bool		found;
+	int32		tdtypmod;
 	MemoryContext oldcxt;
 
 	Assert(tupDesc->tdtypeid == RECORDOID);
@@ -1855,31 +1856,43 @@ assign_record_type_typmod(TupleDesc tupDesc)
 			CreateCacheMemoryContext();
 	}
 
-	/* Find or create a hashtable entry for this tuple descriptor */
+	/* Find a hashtable entry for this tuple descriptor */
 	recentry = (RecordCacheEntry *) hash_search(RecordCacheHash,
 												(void *) &tupDesc,
-												HASH_ENTER, &found);
+												HASH_FIND, &found);
 	if (found && recentry->tupdesc != NULL)
 	{
 		tupDesc->tdtypmod = recentry->tupdesc->tdtypmod;
 		return;
 	}
 
-	/* Not present, so need to manufacture an entry */
-	recentry->tupdesc = NULL;
 	oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
 
 	/* Look in the SharedRecordTypmodRegistry, if attached */
 	entDesc = find_or_make_matching_shared_tupledesc(tupDesc);
+
+	if (entDesc == NULL) 
+	{
+		tdtypmod = NextRecordTypmod++;
+	}
+	else 
+	{
+		tdtypmod = entDesc->tdtypmod;
+	}
+	ensure_record_cache_typmod_slot_exists(tdtypmod);
+	
 	if (entDesc == NULL)
 	{
 		/* Reference-counted local cache only. */
 		entDesc = CreateTupleDescCopy(tupDesc);
 		entDesc->tdrefcount = 1;
-		entDesc->tdtypmod = NextRecordTypmod++;
+		entDesc->tdtypmod = tdtypmod;
 	}
-	ensure_record_cache_typmod_slot_exists(entDesc->tdtypmod);
 	RecordCacheArray[entDesc->tdtypmod] = entDesc;
+	/* Not present, so need to manufacture an entry */
+	recentry = (RecordCacheEntry *) hash_search(RecordCacheHash,
+												(void *) &tupDesc,
+												HASH_ENTER, NULL);
 	recentry->tupdesc = entDesc;
 
 	/* Assign a unique tupdesc identifier, too. */
