Postgresql group by aliased jsonb field

group bypostgresql

I'm trying to group by the result of a jsonb operation on an aliased field, but getting an error I would not expect.

The following work as expected:

select jsonb_build_object('x', 1) as a group by a;
select jsonb_build_object('x', 1) as a group by jsonb_build_object('x', 1)#>>'{x}';

    a     
----------
 {"x": 1}

But this gives me an error:

select jsonb_build_object('x', 1) as a group by a#>>'{x}';
ERROR:  column "a" does not exist

Is this a bug in postgresql (13.3)? Is there any way around it other than repeating the entire select expression in the group by?

Best Answer

You can use an alias (or a number referencing the position in the SELECT list) only when it stands alone and is not used inside an expression.

The documentation is not quite clear about that; all it says is

In case of ambiguity, a GROUP BY name will be interpreted as an input-column name rather than an output column name.