diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c
index faa181207a..bce199a55f 100644
--- a/src/backend/commands/vacuum.c
+++ b/src/backend/commands/vacuum.c
@@ -400,15 +400,17 @@ get_rel_oids(Oid relid, const RangeVar *vacrel)
 		bool		include_parts;
 
 		/*
-		 * Since we don't take a lock here, the relation might be gone, or the
-		 * RangeVar might no longer refer to the OID we look up here.  In the
-		 * former case, VACUUM will do nothing; in the latter case, it will
+		 * Take a lock here for the relation lookup. If ANALYZE or VACUUM spawn
+		 * multiple transactions, the lock taken here will be gone once the
+		 * current transaction running commits, which could cause the relation
+		 * to be gone, or the RangeVar might not refer to the OID looked up here.
+		 * In this case, VACUUM will do nothing; in the latter case, it will
 		 * process the OID we looked up here, rather than the new one. Neither
 		 * is ideal, but there's little practical alternative, since we're
 		 * going to commit this transaction and begin a new one between now
 		 * and then.
 		 */
-		relid = RangeVarGetRelid(vacrel, NoLock, false);
+		relid = RangeVarGetRelid(vacrel, ShareUpdateExclusiveLock, false);
 
 		/*
 		 * To check whether the relation is a partitioned table, fetch its
@@ -430,7 +432,9 @@ get_rel_oids(Oid relid, const RangeVar *vacrel)
 		oldcontext = MemoryContextSwitchTo(vac_context);
 		if (include_parts)
 			oid_list = list_concat(oid_list,
-								   find_all_inheritors(relid, NoLock, NULL));
+								   find_all_inheritors(relid,
+												ShareUpdateExclusiveLock,
+												NULL));
 		else
 			oid_list = lappend_oid(oid_list, relid);
 		MemoryContextSwitchTo(oldcontext);
