Re: subquery/alias question

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Michael Glaesemann <grzm(at)seespotcode(dot)net>
Cc: Alvaro Herrera <alvherre(at)commandprompt(dot)com>, Madison Kelly <linux(at)alteeve(dot)com>, PostgreSQL General <pgsql-general(at)postgresql(dot)org>
Subject: Re: subquery/alias question
Date: 2007-09-26 02:44:40
Message-ID: 11977.1190774680@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Michael Glaesemann <grzm(at)seespotcode(dot)net> writes:
> I believe you'd have to write it like

> select dom_id, dom_name, count(usr_dom_id) as usr_count
> from domains
> join users on (usr_dom_id = dom_id)
> having count(usr_dom_id) > 0
> order by dom_name;

> I don't know how the performance would compare. I think the backend
> is smart enough to know it doesn't need to perform two seq scans to
> calculate count(usr_dom_id), but I wasn't sure.

It has been smart enough for a few years now --- don't recall when
exactly, but nodeAgg.c quoth

* Perform lookups of aggregate function info, and initialize the
* unchanging fields of the per-agg data. We also detect duplicate
* aggregates (for example, "SELECT sum(x) ... HAVING sum(x) > 0"). When
* duplicates are detected, we only make an AggStatePerAgg struct for the
* first one. The clones are simply pointed at the same result entry by
* giving them duplicate aggno values.

... which in English means we just do the calculation once ...

regards, tom lane

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Mike C 2007-09-26 02:52:35 NZDT Question
Previous Message Michael Glaesemann 2007-09-26 02:26:55 Re: subquery/alias question