From: Heikki Linnakangas <hlinnaka@iki.fi>
To: Pg Bugs <pgsql-bugs@postgresql.org>
Subject: Improper const-evaluation of HAVING with grouping sets and subquery pullup
Date: Thu, 12 Oct 2017 14:59:12 +0300
Message-ID: <7dbdcf5c-b5a6-ef89-4958-da212fe10176@iki.fi> (raw)
List-Unsubscribe: <mailto:majordomo@postgresql.org?body=unsub%20pgsql-bugs>
This query produces an incorrect result:
regression=# select four, x
from (select four, ten, 'foo'::text as x from tenk1 ) as t
group by grouping sets(four, x) having x = 'foo' order by four;
four | x
------+-----
0 |
1 |
2 |
3 |
| foo
(5 rows)
The "having x = 'foo'" clause should've filtered out the rows where x is
NULL, leaving only the last row as the result. Even though x is a
constant 'foo' in the subquery, HAVING clause is supposed to be
evaluated after grouping. What happens is that subquery pullup replaces
x with the constant, and the "'foo' = 'foo'" qual is later
const-evaluated to true.
I propose the attached patch to fix that. It forces the use of
PlaceHolderVars in subquery pullup, if the parent query has grouping
sets and HAVING. I'm not 100% sure that's the right approach or a misuse
of the placeholder system, so comments welcome. At first, I tried to set
wrap_non_vars=true only when processing the havingQual, so that
placeholders would only be there. But that didn't work out, I think
because grouping sets planning would then put both the Const, and the
PlaceHolderVar for the Const, in the Agg's targetlist, but only one of
them would be set to NULL when doing the grouping.
Another thing is that the check could be made much tighter, so that
PlaceHolderVars were only used for expressions actually used in the
HAVING. But it didn't seem worth the trouble to me.
- Heikki
Attachments:
0001-Fix-subquery-pullup-into-a-query-containing-GROUPING.patch (text/x-patch, 0B) download
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-bugs@postgresql.org
Cc: hlinnaka@iki.fi
Subject: Re: Improper const-evaluation of HAVING with grouping sets and subquery pullup
In-Reply-To: <7dbdcf5c-b5a6-ef89-4958-da212fe10176@iki.fi>
References: <7dbdcf5c-b5a6-ef89-4958-da212fe10176@iki.fi>
* 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