Received: from maia.hub.org (maia-2.hub.org [200.46.204.251]) by mail.postgresql.org (Postfix) with ESMTP id 2D7E7B5DBFE for ; Tue, 12 Jul 2011 11:28:32 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.251]) (amavisd-maia, port 10024) with ESMTP id 57608-06 for ; Tue, 12 Jul 2011 14:28:26 +0000 (UTC) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from sss.pgh.pa.us (sss.pgh.pa.us [66.207.139.130]) by mail.postgresql.org (Postfix) with ESMTP id 01815B5DBBF for ; Tue, 12 Jul 2011 11:28:25 -0300 (ADT) Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.14.2/8.14.2) with ESMTP id p6CESOlD012016; Tue, 12 Jul 2011 10:28:24 -0400 (EDT) To: Jeff Davis cc: pgsql-bugs@postgresql.org Subject: Re: Window function bug In-reply-to: <1310431686.497.26.camel@jdavis-ux.asterdata.local> References: <1310431686.497.26.camel@jdavis-ux.asterdata.local> Comments: In-reply-to Jeff Davis message dated "Mon, 11 Jul 2011 17:48:06 -0700" Date: Tue, 12 Jul 2011 10:28:24 -0400 Message-ID: <12015.1310480904@sss.pgh.pa.us> From: Tom Lane X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-1.91 tagged_above=-5 required=5 tests=BAYES_00=-1.9, T_RP_MATCHES_RCVD=-0.01 X-Spam-Level: X-Archive-Number: 201107/102 X-Sequence-Number: 30714 Jeff Davis writes: > In branch postgresql/master: > SELECT SUM(SUM(a)) OVER () > FROM (SELECT NULL::int4 AS a WHERE FALSE) R; > ERROR: XX000: cannot extract attribute from empty tuple slot Huh, interesting. > Honestly, I'm not sure what the semantics of that are supposed to be. Is > it even allowed by the standard? Yeah, I believe so. Aggregate calls within window function calls are supposed to be legal. They're not terribly useful unless there's a GROUP BY clause --- when there is, you get a row per group out of the aggregates, and then it's sensible to apply windowing functions on that rowset. This is a pretty degenerate case ... but it ought not fail. After tracing through it, it seems the bug is that the planner generates a targetlist for the Agg node containing "a, SUM(a)", and then when that is evaluated for a case where no row was ever produced by the subquery, the executor quite properly fails, since there's noplace to get a value of "a" from. The targetlist is built by these statements in planner.c: window_tlist = flatten_tlist(tlist); if (parse->hasAggs) window_tlist = add_to_flat_tlist(window_tlist, pull_agg_clause((Node *) tlist)); window_tlist = add_volatile_sort_exprs(window_tlist, tlist, activeWindows); so I guess the answer is that this code ought to avoid adding Vars that are only mentioned within aggregates. Perhaps also omit those only used within volatile sort expressions, though I think that would just be an efficiency issue not a correctness issue, and it may be unreasonably expensive to determine that. regards, tom lane