Thread: BUG #18953: Planner fails to build plan for complex query with LATERAL references

The following bug has been logged on the website:

Bug reference:      18953
Logged by:          Alexander Lakhin
Email address:      exclusion@gmail.com
PostgreSQL version: 18beta1
Operating system:   Ubuntu 24.04
Description:

The following query:
create table tbl1(a int);
create table tbl2(b int);
create table tbl3(c int);
select * from tbl1 left join
  (select case when a = 0 then 0 else subq_3.cc end from tbl1,
    lateral (select 1 from tbl2 t1, tbl2 t2, tbl2 t3, tbl2 t4) subq_1,
    lateral (
      select tbl3.c as cc from tbl3, tbl2 t1, tbl2 t2,
      lateral (select c, a from tbl2 limit 1) subq_2
    ) as subq_3
  ) subq_4 on true;
ends up with:
ERROR:  XX000: failed to build any 4-way joins
LOCATION:  standard_join_search, allpaths.c:3527
where N in "N-way" depends on the number of tbl2 t2, tbl2 t3, ... in
subq_1.
This is a simplified version of a query generated by SQLsmith.
The first commit this error is raised on is acfcd45ca. On acfcd45ca~1, the
select fails with "ERROR:  could not devise a query plan for the given
query". The last commit it executed with no error is 4200a9286.