DROP TABLE IF EXISTS t,t3;
CREATE TABLE t (a int, b int);
CREATE TABLE t3 (a int, b int);
INSERT INTO t (
  SELECT gs%5, gs%5 FROM generate_series(1,100) AS gs);
INSERT INTO t3 (
  SELECT gs, gs FROM generate_series(1,100) AS gs);
CREATE INDEX ON t (a,b);
VACUUM ANALYZE t,t3;

explain (analyze, costs off)
select * from t t0 left join
  (t t1 left join t t2 on t1.a = t2.a
   join lateral
     (select distinct on (a, b) a, b, t0.a+t1.a+t2.a as x
      from t t3 offset 0) t3
         on t1.a = t3.a and coalesce(t2.b) = t3.b)
  on t0.b = t3.b;
  
/*
 Nested Loop Left Join
   ->  Seq Scan on t t0
   ->  Nested Loop
         Join Filter: (COALESCE(t2.b) = t3.b)
         ->  Nested Loop Left Join
               ->  Index Only Scan using t_a_b_idx on t t1
               ->  Memoize
                     Cache Key: t1.a
                     Cache Mode: logical
                     ->  Index Only Scan using t_a_b_idx on t t2
                           Index Cond: (a = t1.a)
         ->  Memoize
               Cache Key: t3.b, t1.a, t0.a, t2.a
               Cache Mode: binary
               ->  Subquery Scan on t3
                     Filter: ((t0.b = t3.b) AND (t1.a = t3.a))
                     ->  Unique
                           ->  Sort
                                 Sort Key: t3_1.a, t3_1.b
                                 ->  Seq Scan on t t3_1
*/

