create table aa1 (a int, b int);
create table aa2 (a int, b int);
create table bb (b int, c int);
create table ai (a int);

insert into aa1 select a, a % 100000 from generate_series(1, 1000000) a;
alter table aa1 add primary key(a);
vacuum analyze aa1;

insert into aa2 select a, a % 100000 from generate_series(1, 1000000) a;
alter table aa2 add primary key(a);
vacuum analyze aa2;

insert into bb select b, b % 10 from generate_series(1, 100000) b;
alter table bb add primary key(b);
vacuum analyze bb;

insert into ai values (111), (222);
vacuum analyze ai;

explain analyze
SELECT *
FROM (
       SELECT a, b
       FROM aa1
    UNION ALL
       SELECT a, b
       FROM aa2
) aa
join bb using (b)
WHERE aa.a in (select a from ai);

\g

\g

drop table aa1, aa2, bb, ai;
