Re: How can the Aggregation move to the outer query

From: Andy Fan <zhihui(dot)fan1213(at)gmail(dot)com>
To: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Cc: David Rowley <dgrowleyml(at)gmail(dot)com>, PostgreSQL Hackers <pgsql-hackers(at)lists(dot)postgresql(dot)org>
Subject: Re: How can the Aggregation move to the outer query
Date: 2021-05-25 16:25:41
Message-ID: CAKU4AWp_jMZ9jp48tO_MjqWnfA6Du7FCF1fXzN9HMzf-e5+VLg@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On Tue, May 25, 2021 at 10:23 PM Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us> wrote:

> David Rowley <dgrowleyml(at)gmail(dot)com> writes:
> > On Tue, 25 May 2021 at 22:28, Andy Fan <zhihui(dot)fan1213(at)gmail(dot)com> wrote:
> >> explain (costs off) select (select count(*) filter (where t2.b = 1)
> from m1 t1)
> >> from m1 t2 where t2.b % 2 = 1;
> >>
> >> This one is too confusing to me since the Aggregate happens
> >> on t2 rather than t1. What happens here? Would this query
> >> generate 1 row all the time like SELECT aggfunc(a) FROM t?
>
> > I think you're misreading the plan. There's a scan on t2 with a
> > subplan then an aggregate on top of that. Because you made the
> > subquery correlated by adding t2.b, it cannot be executed as an
> > initplan.
>
> Also keep in mind that adding that filter clause completely changed
> the meaning of the aggregate. Aggregates belong to the lowest
> query level containing any Var used in their arguments, so that
> where in your original query the count(*) was an aggregate of the
> subquery, now it's an aggregate of the outer query (and the subquery
> now perceives it as a constant outer reference). AFAIR this is per
> SQL spec.
>

Well, finally I know it's an aggregate of the outer query.. Thank you for
the explanation! so I would say the result set has 1 row for that query
all the time.

--
Best Regards
Andy Fan (https://www.aliyun.com/)

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message Robert Haas 2021-05-25 16:46:45 storing an explicit nonce
Previous Message Justin Pryzby 2021-05-25 16:14:58 Re: array_cat anycompatible change is breaking xversion upgrade tests