diff --git a/src/bin/psql/mainloop.c b/src/bin/psql/mainloop.c
index e49ed02293..3b7b4ad4a2 100644
--- a/src/bin/psql/mainloop.c
+++ b/src/bin/psql/mainloop.c
@@ -564,9 +564,20 @@ MainLoop(FILE *source)
 				break;
 		}
 
-		/* Add line to pending history if we didn't execute anything yet */
-		if (pset.cur_cmd_interactive && !line_saved_in_history)
-			pg_append_history(line, history_buf);
+		/*
+		 * Add line to pending history if we didn't do so already.  Then, if
+		 * the query buffer is still empty, flush out any unsent history
+		 * entry.  This means that empty lines (containing only whitespace and
+		 * perhaps a dash-dash comment) that precede a query will be recorded
+		 * as separate history entries, not as part of that query.
+		 */
+		if (pset.cur_cmd_interactive)
+		{
+			if (!line_saved_in_history)
+				pg_append_history(line, history_buf);
+			if (query_buf->len == 0)
+				pg_send_history(history_buf);
+		}
 
 		psql_scan_finish(scan_state);
 		free(line);
