Re: BUG #14746: sub query's plan not right?

Feike Steenbergen <feikesteenbergen@gmail.com>

From: Feike Steenbergen <feikesteenbergen@gmail.com>
To: digoal@126.com
Cc: PostgreSQL mailing lists <pgsql-bugs@postgresql.org>
Date: 2017-07-26T08:58:59Z
Lists: pgsql-bugs
> is this a bug ? or it can be improved?

Perhaps, for me it rings a bell of using OFFSET 0 as a hack, that at least
has
the property of not changing the logic of your query:

select (t.b).aid,(t.b).val,(t.b).crt_time
from
(
  select
    (
      select b from b
        where b.aid=a.id
        order by crt_time desc limit 1
    )
  from a offset 0
) t
where (t.b).aid is not null;

Previous similar discussion:

https://www.postgresql.org/message-id/E1RfAwz-0006Us-7B%40wrigleys.postgresql.org

Some other pointers:
https://blog.2ndquadrant.com/postgresql-ctes-are-optimization-fences/
https://stackoverflow.com/questions/14897816/how-can-i-prevent-postgres-from-inlining-a-subquery