diff --git a/src/backend/utils/cache/relfilenodemap.c b/src/backend/utils/cache/relfilenodemap.c
index db6bb1c1fd..df3e11943c 100644
--- a/src/backend/utils/cache/relfilenodemap.c
+++ b/src/backend/utils/cache/relfilenodemap.c
@@ -133,7 +133,12 @@ InitializeRelfilenodeMap(void)
 
 /*
  * Map a relation's (tablespace, filenode) to a relation's oid and cache the
- * result.
+ * result. If both permanent and temporary relations are found, persistent one
+ * is chosen.
+ *
+ * XXXX: This behavior is valid for most use cases, except for the SQL function
+ * pg_lation_filenode(), which can handle temporary relations. In all other
+ * cases, this function is intended fo ruse with permanent relations only.
  *
  * Returns InvalidOid if no relation matching the criteria could be found.
  */
@@ -186,6 +191,8 @@ RelidByRelfilenode(Oid reltablespace, Oid relfilenode)
 	}
 	else
 	{
+		bool is_temp = false;
+
 		/*
 		 * Not a shared table, could either be a plain relation or a
 		 * non-shared, nailed one, like e.g. pg_class.
@@ -213,9 +220,21 @@ RelidByRelfilenode(Oid reltablespace, Oid relfilenode)
 		while (HeapTupleIsValid(ntp = systable_getnext(scandesc)))
 		{
 			if (found)
-				elog(ERROR,
-					 "unexpected duplicate for tablespace %u, relfilenode %u",
-					 reltablespace, relfilenode);
+			{
+				Form_pg_class classform = (Form_pg_class) GETSTRUCT(ntp);
+
+				/* check if the same entry for the same persistency exists */
+				if (is_temp ?
+					classform->relpersistence == RELPERSISTENCE_TEMP :
+					classform->relpersistence != RELPERSISTENCE_TEMP)
+					elog(ERROR,
+						 "unexpected duplicate for tablespace %u, relfilenode %u",
+						 reltablespace, relfilenode);
+
+				/* prioritize non-temporary if both are found */
+				if (!is_temp)
+					continue;
+			}
 			found = true;
 
 #ifdef USE_ASSERT_CHECKING
@@ -240,6 +259,10 @@ RelidByRelfilenode(Oid reltablespace, Oid relfilenode)
 		systable_endscan(scandesc);
 		heap_close(relation, AccessShareLock);
 
+		/* don't cache the relid if it is a temp relation */
+		if (is_temp && found)
+			return relid;
+
 		/* check for tables that are mapped but not shared */
 		if (!found)
 			relid = RelationMapFilenodeToOid(relfilenode, false);
