diff --git a/src/backend/utils/cache/relfilenodemap.c b/src/backend/utils/cache/relfilenodemap.c
index 56d7c73d33..e9ae548a4b 100644
--- a/src/backend/utils/cache/relfilenodemap.c
+++ b/src/backend/utils/cache/relfilenodemap.c
@@ -130,7 +130,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.
  */
@@ -183,6 +188,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.
@@ -212,9 +219,19 @@ RelidByRelfilenode(Oid reltablespace, Oid relfilenode)
 			Form_pg_class classform = (Form_pg_class) GETSTRUCT(ntp);
 
 			if (found)
-				elog(ERROR,
-					 "unexpected duplicate for tablespace %u, relfilenode %u",
-					 reltablespace, relfilenode);
+			{
+				/* 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;
 
 			Assert(classform->reltablespace == reltablespace);
@@ -225,6 +242,10 @@ RelidByRelfilenode(Oid reltablespace, Oid relfilenode)
 		systable_endscan(scandesc);
 		table_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);
