diff --git a/src/bin/pg_upgrade/upgrade_adapt.sql b/src/bin/pg_upgrade/upgrade_adapt.sql
index 54920f54f5..4acad18f60 100644
--- a/src/bin/pg_upgrade/upgrade_adapt.sql
+++ b/src/bin/pg_upgrade/upgrade_adapt.sql
@@ -97,23 +97,19 @@ DROP OPERATOR public.#@%# (pg_catalog.int8, NONE);
 \if :oldpgversion_le15
 DO $$
   DECLARE
-    rec text;
-	col text;
+    rec record;
   BEGIN
   FOR rec in
-    SELECT oid::regclass::text
-    FROM pg_class
-    WHERE relname !~ '^pg_'
-      AND relkind IN ('r')
+    SELECT oid::regclass::text as rel, attname as col
+    FROM pg_class c, pg_attribute a
+    WHERE c.relname !~ '^pg_'
+      AND c.relkind IN ('r')
+      AND a.attrelid = c.oid
+      AND a.atttypid = 'aclitem'::regtype
     ORDER BY 1
   LOOP
-    FOR col in SELECT attname FROM pg_attribute
-      WHERE attrelid::regclass::text = rec
-      AND atttypid = 'aclitem'::regtype
-    LOOP
-      EXECUTE 'ALTER TABLE ' || quote_ident(rec) || ' ALTER COLUMN ' ||
-        quote_ident(col) || ' SET DATA TYPE text';
-    END LOOP;
+    EXECUTE 'ALTER TABLE ' || quote_ident(rec.rel) || ' ALTER COLUMN ' ||
+      quote_ident(rec.col) || ' SET DATA TYPE text';
   END LOOP;
   END; $$;
 \endif
