FROM graph5 td JOIN graph6 gtt ON gtt.id=td.entity_type_id JOIN graph2 gcr ON gcr.id=ANY(td.detail_id) JOIN graph3 gtd ON gtd.id=gcr.t_ids JOIN graph1 glt ON glt.id=ANY(gtd.id_list);
I've ordered joins (well, tables) in the way they depend on each other.
I would try out to move the first join into the CTE in order to isolate it's results
and help optimizer to better estiamte the rows. Something like this: