Original query:

SELECT  (SELECT start_date FROM arm_int2.datastream_info WHERE datastream ILIKE $1 ORDER BY start_date LIMIT $11) as original_pub_date,(with sites_info as         ( select site_code || $12 || CASE                 WHEN site_type = $13                 THEN $14                 ELSE site_name                 END ||                 $15 || upper(site_code) ||$16 as agg_sites        FROM arm_int2.site_info         WHERE site_code IN                 (SELECT DISTINCT site_code FROM arm_int2.datastream_info                 WHERE datastream ILIKE $2                 order by site_code)        order by site_type DESC, site_code ASC        ) SELECT string_agg(agg_sites, $17) from sites_info) as sites,(SELECT string_agg(DISTINCT di.site_code || $18 || di.facility_code || $19 || fi.facility_name || $20 || upper(di.facility_code) || $21, $22) as facility_info FROM arm_int2.datastream_info di LEFT JOIN arm_int2.facility_info fi ON (di.site_code = fi.site_code AND di.facility_code = fi.facility_code)WHERE datastream ILIKE $3) as facilities, ((SELECT doi FROM arm_int2.instr_code_to_doi WHERE instrument_code = (SELECT instrument_code FROM arm_int2.datastream_info WHERE datastream ILIKE $4 LIMIT $23) LIMIT $24) UNION ALL (SELECT doi FROM arm_int2.doi_details WHERE instrument_code = (SELECT instrument_code FROM arm_int2.datastream_info WHERE datastream ILIKE $5 LIMIT $25) LIMIT $26) LIMIT $27) as doi,(SELECT instrument_code FROM arm_int2.datastream_info WHERE datastream ILIKE $6 LIMIT $28) as instr_code, (SELECT string_agg(DISTINCT substring(p.name_first FROM $29 FOR $30) || $31 || p.name_last, $32) as name FROM people.people AS p LEFT JOIN people.group_role gr ON (p.person_id = gr.person_id) LEFT JOIN arm_int2.datastream_instrument_class ic ON (upper(gr.role_name) = upper(ic.instrument_class)) WHERE (upper(gr.group_name) = $33 OR upper(gr.group_name) = $34 OR upper(gr.group_name) = $35) AND ic.datastream ILIKE $7) as contact, (SELECT string_agg(DISTINCT p.name_first || $36 || p.name_last || $37 || substring(p.name_first FROM $38 FOR $39), $40) as name FROM people.people AS p LEFT JOIN people.group_role gr ON (p.person_id = gr.person_id) LEFT JOIN arm_int2.datastream_instrument_class ic ON (upper(gr.role_name) = upper(ic.instrument_class)) WHERE (upper(gr.group_name) = $41 OR upper(gr.group_name) = $42 OR upper(gr.group_name) = $43) AND ic.datastream ILIKE $8) as contacts, (SELECT instrument_code FROM arm_int2.datastream_info WHERE datastream ILIKE $9 LIMIT $44) as instr_code, (SELECT instrument_class_name FROM arm_int2.instr_class_details WHERE instrument_class_code = (SELECT instrument_class_code FROM arm_int2.datastream_info WHERE datastream ILIKE $10 LIMIT $45)) as instr_class_name