diff --git a/src/backend/postmaster/pgstat.c b/src/backend/postmaster/pgstat.c
index 3dc280a48d70c58f29e72840b90e9637a455c65a..e355cdee953718cb7a2d1c32525be2d16c2c99b0 100644
--- a/src/backend/postmaster/pgstat.c
+++ b/src/backend/postmaster/pgstat.c
@@ -2581,7 +2581,11 @@ pgstat_bestart(void)
 	beentry->st_databaseid = MyDatabaseId;
 	beentry->st_userid = userid;
 	beentry->st_clientaddr = clientaddr;
-	beentry->st_clienthostname[0] = '\0';
+	if (MyProcPort && MyProcPort->remote_hostname)
+		strlcpy(beentry->st_clienthostname, MyProcPort->remote_hostname,
+				NAMEDATALEN);
+	else
+		beentry->st_clienthostname[0] = '\0';
 	beentry->st_waiting = false;
 	beentry->st_state = STATE_UNDEFINED;
 	beentry->st_appname[0] = '\0';
@@ -2594,9 +2598,6 @@ pgstat_bestart(void)
 	beentry->st_changecount++;
 	Assert((beentry->st_changecount & 1) == 0);
 
-	if (MyProcPort && MyProcPort->remote_hostname)
-		strlcpy(beentry->st_clienthostname, MyProcPort->remote_hostname, NAMEDATALEN);
-
 	/* Update app name to current GUC setting */
 	if (application_name)
 		pgstat_report_appname(application_name);
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 140704f97ca4d538a879b8e5e37fc2a30f8cb437..bf3084fce67ff37fadf1536e1bf5d3bfe01c8056 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -760,7 +760,8 @@ pg_stat_get_activity(PG_FUNCTION_ARGS)
 						clean_ipv6_addr(beentry->st_clientaddr.addr.ss_family, remote_host);
 						values[11] = DirectFunctionCall1(inet_in,
 											   CStringGetDatum(remote_host));
-						if (beentry->st_clienthostname)
+						if (beentry->st_clienthostname &&
+							beentry->st_clienthostname[0])
 							values[12] = CStringGetTextDatum(beentry->st_clienthostname);
 						else
 							nulls[12] = true;