drop table ref_0;

create table ref_0 as select repeat('abcde', (random() * 10)::integer) t, random() * 1000 i from generate_series(1, 500000);

create index on ref_0 (i);

set enable_hashagg=off;
set enable_incremental_sort=off;
set enable_seqscan=off;
set parallel_setup_cost=10;
set parallel_tuple_cost=0;

explain (verbose) select distinct
        subq_0.c1 as c0,
        case when (0.5 = random()) then
                ref_0.t else ref_0.t
        end
             as c4
        from
          public.ref_0,
          lateral (select

                ref_0.i as c1
              from
                generate_series(1, 100) as ref_1) as subq_0;

explain (verbose) select
        subq_0.c1 as c0,
        case when (0.5 = random()) then
                ref_0.t else ref_0.t
        end
             as c4
        from
          public.ref_0,
          lateral (select

                ref_0.i as c1
              from
                generate_series(1, 100) as ref_1) as subq_0 order by 1, 2;

explain (verbose) select
        subq_0.c1 as c0,
        case when (0.5 = random()) then
                ref_0.t else ref_0.t
        end
             as c4
        from
          public.ref_0,
          lateral (select

                ref_0.i as c1
              from
                generate_series(1, 100) as ref_1) as subq_0 group by 1, 2;


-- non-volatile expressions, get pushed down and thus work fine
explain (verbose) select distinct
        subq_0.c1 as c0,
        case when (1.0 = ref_0.i * 2) then
                ref_0.t else ref_0.t
        end
             as c4
        from
          public.ref_0,
          lateral (select

                ref_0.i as c1
              from
                generate_series(1, 100) as ref_1) as subq_0;

explain (verbose) select
        subq_0.c1 as c0,
        case when (1.0 = ref_0.i * 2) then
                ref_0.t else ref_0.t
        end
             as c4
        from
          public.ref_0,
          lateral (select

                ref_0.i as c1
              from
                generate_series(1, 100) as ref_1) as subq_0 order by 1, 2;

explain (verbose) select
        subq_0.c1 as c0,
        case when (1.0 = ref_0.i * 2) then
                ref_0.t else ref_0.t
        end
             as c4
        from
          public.ref_0,
          lateral (select

                ref_0.i as c1
              from
                generate_series(1, 100) as ref_1) as subq_0 group by 1, 2;
