Re: group by can use alias from select list but not the having clause - Mailing list pgsql-bugs

From Pantelis Theodosiou
Subject Re: group by can use alias from select list but not the having clause
Date
Msg-id CAE3TBxyWiQ6RnBJT0=gP5RRGANQ3d_MkR38b_8NGYLDAsGr1zw@mail.gmail.com
Whole thread Raw
In response to Re: group by can use alias from select list but not the having clause  (Tom Lane <tgl@sss.pgh.pa.us>)
List pgsql-bugs


On Mon, Jul 3, 2023 at 3:12 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:
hape Hape <postgres-hape@gmx.de> writes:
> works (how does the group by know about otto if the sequence is done as
> described above?)

This is intentional and documented, eg
https://www.postgresql.org/docs/current/sql-select.html#SQL-GROUPBY
says

    An expression used inside a grouping_element can be an input column
    name, or the name or ordinal number of an output column (SELECT list
    item), or an arbitrary expression formed from input-column values.

whereas the discussion of HAVING does not mention allowing output
columns.  The reason for this is mainly that it'd seldom be useful
for a HAVING expression to be just a bare column reference, but
as soon as you write something that's not a bare column reference,
the output-column special case is disallowed anyway.

Tom, the HAVING clause section has: 

> ... Each column referenced in condition must unambiguously reference a grouping column, ...

I suppose "grouping column" can be read to mean what is called "grouping element" in GROUP BY section and that it may be either input or output column, leading to the confusion.
Perhaps this phrase can be improved to make this clearer.

Best regards
Pantelis Theodosiou

pgsql-bugs by date:

Previous
From: Tom Lane
Date:
Subject: Re: group by can use alias from select list but not the having clause
Next
From: Thomas Munro
Date:
Subject: Re: BUG #17949: Adding an index introduces serialisation anomalies.