Hi, this is a stock PGDG 9.6:
postgres=# with i(x) as (values (1::int)), j(y) as (values (2::int)) select x from (select x from i union all select y from j) b; x --- 1 2 (2 rows) postgres=# with i(x) as (values (1::int)), j(y) as (values (2::int)) select max(x) from (select x from i union all select y from j) b; ERROR: could not find plan for CTE "i" The same on 9.5: postgres=# with i(x) as (values (1::int)), j(y) as (values (2::int)) select x from (select x from i union all select y from j) b; x --- 1 2 (2 rows) postgres=# with i(x) as (values (1::int)), j(y) as (values (2::int)) select max(x) from (select x from i union all select y from j) b; max ----- 2 (1 row) Is this a bug or is my assumption that this should work wrong? Both the aggregate and the UNION are required to trigger the bug: postgres=# with i(x) as (values (1::int)) select x from (select x from i union all select 3::int) b; x --- 1 3 (2 rows) postgres=# with i(x) as (values (1::int)) select max(x) from (select x from i) b; max ----- 1 (1 row) postgres=# with i(x) as (values (1::int)) select max(x) from (select x from i union all select 3::int) b; ERROR: could not find plan for CTE "i" Thanks, Torsten