Re: ***SPAM*** Re: Can I get the number of results plus the results with a single query?

From: David Rowley <dgrowleyml(at)gmail(dot)com>
To: Walter Dörwald <walter(at)livinglogic(dot)de>
Cc: Rob Sargent <robjsargent(at)gmail(dot)com>, pgsql-general(at)lists(dot)postgresql(dot)org
Subject: Re: ***SPAM*** Re: Can I get the number of results plus the results with a single query?
Date: 2022-08-16 09:58:52
Message-ID: CAApHDvrmpeqM0k2teGsy2ep24EqEsFzbGQsTgy44dN3qwnHRtw@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Tue, 16 Aug 2022 at 21:15, Walter Dörwald <walter(at)livinglogic(dot)de> wrote:
> select count(*) over (), e.* from email.email e;

Depending on the complexity of the query, putting the count(*) as a
subquery in the SELECT clause might execute more quickly. i.e. select
(select count(*) from email.email) c, * from email.emails; A
non-correlated subquery will become an "initplan", which will execute
only once.

The reason the window aggregate might be slower is due to the fact
that internally PostgreSQL will store tuples in the window frame in a
tuplestore. In this example, all rows will be put in that tuple store
at once. These tuple stores will spill to disk when they exceed
work_mem. On the other hand, the window aggregate version could be
faster if fetching each tuple from the outer query was sufficiently
more expensive than storing it in a tuple store. That could easily
happen if the query contained expensive joins or many rows were
filtered out. That could be more expensive as the subquery version
would have to do that twice whereas the window agg version would only
have to do that once.

David

In response to

Browse pgsql-general by date

  From Date Subject
Next Message houzj.fnst@fujitsu.com 2022-08-16 11:57:17 RE: Support logical replication of DDLs
Previous Message Walter Dörwald 2022-08-16 09:15:14 Re: ***SPAM*** Re: Can I get the number of results plus the results with a single query?