diff --git a/src/bin/psql/help.c b/src/bin/psql/help.c
index 4883ebd2ed..54fe099ad7 100644
--- a/src/bin/psql/help.c
+++ b/src/bin/psql/help.c
@@ -592,12 +592,12 @@ helpSQL(const char *topic, unsigned short int pager)
 								 * word(s) */
 			{
 				wordlen = j = 1;
-				while (topic[j] != ' ' && j++ < len)
+				while (j < len && topic[j++] != ' ')
 					wordlen++;
-				if (x == 2)
+				if (x == 2 && j < len)
 				{
-					j++;
-					while (topic[j] != ' ' && j++ <= len)
+					wordlen++;
+					while (j < len && topic[j++] != ' ')
 						wordlen++;
 				}
 				if (wordlen >= len) /* Don't try again if the same word */
