diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c
index 584922b340..b89f500902 100644
--- a/src/interfaces/libpq/fe-protocol3.c
+++ b/src/interfaces/libpq/fe-protocol3.c
@@ -962,9 +962,21 @@ pqGetErrorNotice3(PGconn *conn, bool isError)
 	 * Save the active query text, if any, into res as well; but only if we
 	 * might need it for an error cursor display, which is only true if there
 	 * is a PG_DIAG_STATEMENT_POSITION field.
+	 *
+	 * Note that in pipeline mode, we have not yet advanced the query pointer
+	 * to the next query, so we have to look at that.
 	 */
-	if (have_position && conn->last_query && res)
-		res->errQuery = pqResultStrdup(res, conn->last_query);
+	if (have_position && res)
+	{
+		if (conn->pipelineStatus != PQ_PIPELINE_OFF &&
+			conn->asyncStatus == PGASYNC_IDLE)
+		{
+			if (conn->cmd_queue_head)
+				res->errQuery = pqResultStrdup(res, conn->cmd_queue_head->query);
+		}
+		else if (conn->last_query)
+			res->errQuery = pqResultStrdup(res, conn->last_query);
+	}
 
 	/*
 	 * Now build the "overall" error message for PQresultErrorMessage.
