Re: Weirdness (bug?) with aggregates and subqueries - Mailing list pgsql-general

From Tom Lane
Subject Re: Weirdness (bug?) with aggregates and subqueries
Date
Msg-id 762198.1699479391@sss.pgh.pa.us
Whole thread Raw
In response to Weirdness (bug?) with aggregates and subqueries  (Laurenz Albe <laurenz.albe@cybertec.at>)
Responses Re: Weirdness (bug?) with aggregates and subqueries
List pgsql-general
Laurenz Albe <laurenz.albe@cybertec.at> writes:
> I found this in a blog (https://buttondown.email/jaffray/archive/sql-scoping-is-surprisingly-subtle-and-semantic/):
>   CREATE TABLE aa (a INT);
>   INSERT INTO aa VALUES (1), (2), (3);
>   CREATE TABLE xx (x INT);
>   INSERT INTO xx VALUES (10), (20), (30);

>   SELECT (SELECT sum(a) FROM xx LIMIT 1) FROM aa;

>    sum
>   ═════
>      6
>   (1 row)

> Huh?  Shouldn't that return three rows, just like

No.  The aggregate function is semantically of the closest query level
that contributes a Var to its argument, so it's evaluated at the "FROM
aa" level, causing that level to become an aggregated query that
returns just one row.  Then it acts like an outer reference as far
as the sub-select is concerned.  This is documented at the end of
Section 4.2.7 in our manual,

https://www.postgresql.org/docs/current/sql-expressions.html#SYNTAX-AGGREGATES

Thank the SQL spec for that weirdness.

            regards, tom lane



pgsql-general by date:

Previous
From: Laurenz Albe
Date:
Subject: Weirdness (bug?) with aggregates and subqueries
Next
From: yangsr3411
Date:
Subject: Re: Server process exited with exit code 4