pg.ddx.io  pgsql-general@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Laurenz Albe <laurenz.albe@cybertec.at>
To: pgsql-general@lists.postgresql.org
Subject: Weirdness (bug?) with aggregates and subqueries
Date: Wed, 08 Nov 2023 22:12:59 +0100
Message-ID: <895f34d19556dda5ff3319b584198df20085e596.camel@cybertec.at> (raw)

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

  SELECT (SELECT sum(14) FROM xx LIMIT 1) FROM aa;

   sum 
  ═════
    42
    42
    42
  (3 rows)

Looking at the plan of the weird query, the aggregate seems to be in the wrong place:

  EXPLAIN (COSTS OFF) SELECT (SELECT sum(a) FROM xx LIMIT 1) FROM aa;

            QUERY PLAN          
  ══════════════════════════════
   Aggregate
     ->  Seq Scan on aa
     SubPlan 1
       ->  Limit
             ->  Seq Scan on xx
  (5 rows)


And this gives an error:

  SELECT a, (SELECT sum(a) FROM xx LIMIT 1) FROM aa;
  ERROR:  column "aa.a" must appear in the GROUP BY clause or be used in an aggregate function
  LINE 1: SELECT a, (SELECT sum(a) FROM xx LIMIT 1) FROM aa;
                 ^

I think that the optimizer is going astray here...

But perhaps I am missing something obvious.

Yours,
Laurenz Albe





view thread (3+ messages)  latest in thread

Message-ID: <895f34d19556dda5ff3319b584198df20085e596.camel@cybertec.at>
Permalink:  ../895f34d19556dda5ff3319b584198df20085e596.camel@cybertec.at/
Also on:    postgresql.org/message-id/895f34d19556dda5ff3319b584198df20085e596.camel@cybertec.at

 · 

reply

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: laurenz.albe@cybertec.at
  Subject: Re: Weirdness (bug?) with aggregates and subqueries
  In-Reply-To: <895f34d19556dda5ff3319b584198df20085e596.camel@cybertec.at>
  References: <895f34d19556dda5ff3319b584198df20085e596.camel@cybertec.at>

* 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