Subject: Re: Will PQsetSingleRowMode get me results faster?

From: Tom Lane <[email-masked]>
Date: Mon, 06 Jan 2025 15:06:21 -0500

"Daniel Verite" <[email-masked]> writes:
> 	Stijn Sanders wrote:
>> From what I notice using LibPQ, it appears a query needs to complete
>> before resulting data is being transferred to the client. Please
>> correct me if I'm wrong.

> No, the query does not need to complete. If you run something like
> "select * from bigtable" in single-row or chunked mode, you should
> see that the first results are typically available immediately to the
> application, while the query is far from finished.
> But it depends on the query plan. A lot of queries cannot produce any
> result until the final stage of their execution. For these, you can't
> expect any difference in how fast the first results are available
> client-side.

Right.  But there's yet another moving part here: when creating
a plan for a cursor query, the planner will give some preference
(not infinite preference, but some) to plans that are expected
to produce their first result row sooner.  For example it might
pick an indexscan plan on a suitably-ordered index over a
seqscan-and-sort plan, even if the indexscan is estimated to take
more time to run to completion.

So in principle, you might get best results by defining your query
with DECLARE CURSOR and then using PQsetSingleRowMode on the FETCH.
But it'd really depend on the particular query whether this gives
any benefit.

			regards, tom lane

---

From: Stijn Sanders <[email-masked]>
Date: Fri, 4 Apr 2025 13:41:17 +0200

> But it'd really depend on the particular query whether this gives

That's a really nice suggestion, and it took me some time to set up a
suitable test environment to see if it would work, but using separate
PQsendquery/PQexec calls for:

start transaction read only
declare cr1 no scroll cursor for select (and the rest of my query)
fetch next in cr1

it seems like the fetch instruction still takes about as much time as
the full 'normal' select would, I tried a few different queries, but
I'm still suspecting PostgreSQL's internals is waiting for the data to
all 'be ready' before it can send any data over, even if these
PQgetResult's for each fetch will have a PQntuples of 1.
(I even tried with "fetch 8", and PQntuples neatly serves 8 at a time,
but still after about the same time PQsendquery(,'select... would
take)
Or could there still be something that I'm doing that prevents 'firehosing'?