diff --git a/contrib/pg_stat_statements/pg_stat_statements.c b/contrib/pg_stat_statements/pg_stat_statements.c
index 2f069b7..9be9305 100644
--- a/contrib/pg_stat_statements/pg_stat_statements.c
+++ b/contrib/pg_stat_statements/pg_stat_statements.c
@@ -53,6 +53,7 @@
 #include "parser/analyze.h"
 #include "parser/parsetree.h"
 #include "parser/scanner.h"
+#include "parser/gram.h"
 #include "pgstat.h"
 #include "storage/fd.h"
 #include "storage/ipc.h"
@@ -2141,6 +2142,12 @@ fill_in_constant_lengths(pgssJumbleState *jstate, const char *query)
 						break;	/* out of inner for-loop */
 				}
 
+				/* Skip tokens other than constants */
+				if (!(tok == FCONST || tok == SCONST || tok == BCONST ||
+					  tok == XCONST || tok == ICONST || tok == NULL_P ||
+					  tok == TRUE_P || tok == FALSE_P))
+					break;	/* out of inner for-loop */
+
 				/*
 				 * We now rely on the assumption that flex has placed a zero
 				 * byte after the text of the current token in scanbuf.
