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

From: Bryn Llewellyn <bryn(at)yugabyte(dot)com>
To: pedz(at)easesoftware(dot)com
Cc: pgsql-general list <pgsql-general(at)lists(dot)postgresql(dot)org>, "Peter J(dot) Holzer" <hjp-pgsql(at)hjp(dot)at>, "David G(dot) Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com>
Subject: Re: Can I get the number of results plus the results with a single query?
Date: 2022-08-15 19:20:44
Message-ID: C6C274DF-62A3-4E54-AC83-F0FB3D7017EC@yugabyte.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

>>> pedz(at)easesoftware(dot)com <mailto:pedz(at)easesoftware(dot)com> wrote:
>>>
>>> Currently I’m doing this with two queries such as:
>>>
>>> SELECT COUNT(*) FROM table WHERE …. expression …
>>> SELECT * FROM table WHERE …. expression …
>>>
>>> But this requires two queries. Is there a way to do the same thing with just one quer?
>>
>> david(dot)g(dot)johnston(at)gmail(dot)com wrote:
>>
>> Use count as a window function.
>
> hjp-pgsql(at)hjp(dot)at wrote:
>
> I don't think there can be [a way to do the same thing with just one query].

How about this:

create table t(k serial primary key, v int not null);
insert into t(v) values (7), (19), (42), (57), (100), (200), (300);

create function f()
returns table(z text)
language plpgsql
stable
as $body$
declare
r int not null := 0;
results constant int[] :=
(
select array_agg(v order by v) from t where v < 100
);
begin
z := 'Count(*): '||cardinality(results); return next;

foreach r in array results loop
z := r::int; return next;
end loop;
end;
$body$;

select f();

It suns without error and gets this result:

Count(*): 4
7
19
42
57

Is this what you want, Perry? B.t.w., your second "count(*)" might give a misleading answer unless you use "repeatable read" or "serializable"—and it's generally a good plan to avoid those isolation levels unless your use case forces no other choice.

I've never heard anybody say that this "bulk collect" approach (using Oracle Database's vocabulary) harms performance. Does anybody think that it might?

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Perry Smith 2022-08-15 20:37:12 Re: ***SPAM*** Re: Can I get the number of results plus the results with a single query?
Previous Message Peter J. Holzer 2022-08-15 18:16:18 Re: Can I get the number of results plus the results with a single query?