Hi Jeff,
On Wed, Sep 20, 2017 at 10:16 PM, Jeff Janes <jeff.janes@xxxxxxxxx> wrote:
On Tue, Sep 19, 2017 at 7:31 PM, monika yadav <monika.1234yadav@xxxxxxxxx> wrote:Hi All,I didn't understand why same sub plan for the sub query executed two times? As per the query it should have been executed only once.Can someone please explain this behaviour of query execution ?The sum_bid at the end of the query is an alias for the entire subselect, so it not entirely surprising that it gets interpolated twice. it is just kind of unfortunate from a performance perspective.The query I originally gave is equivalent to this query:selectaid,(select sum(bid) from pgbench_brancheswhere bbalance between -10000-abalance and 1+abalance) as sum_bidfrom pgbench_accountswhere aid between 1 and 1000group by aidhaving (select sum(bid) from pgbench_branches where bbalance between -10000-abalance and 1+abalance ) >0;In my originally query I just wrapped the whole thing in another select, so that I could use the alias rather than having to mechanically repeat the entire subquery again in the HAVING section. They give identical plans.Cheers,Jeff