From: Tom Lane <tgl@sss.pgh.pa.us>
To: Laurenz Albe <laurenz.albe@cybertec.at>
Cc: pgsql-general@lists.postgresql.org
Subject: Re: Weirdness (bug?) with aggregates and subqueries
Date: Wed, 08 Nov 2023 16:36:31 -0500
Message-ID: <762198.1699479391@sss.pgh.pa.us> (raw)
In-Reply-To: <895f34d19556dda5ff3319b584198df20085e596.camel@cybertec.at>
References: <895f34d19556dda5ff3319b584198df20085e596.camel@cybertec.at>
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
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients from your mail client; the link fills in
the headers below: reply via email
Some clients, webmail especially, drop In-Reply-To and References from
a link, and the reply then starts a new thread: use the mbox below.
To: pgsql-general@postgresql.org
Cc: tgl@sss.pgh.pa.us, laurenz.albe@cybertec.at
Subject: Re: Weirdness (bug?) with aggregates and subqueries
In-Reply-To: <762198.1699479391@sss.pgh.pa.us>
References: <895f34d19556dda5ff3319b584198df20085e596.camel@cybertec.at> <762198.1699479391@sss.pgh.pa.us>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox