My sql statement is written using cross join lateral in postgres sql. But i want to execute this sql statement in google bigquery and bigquery doesn’t support cross join lateral. How can i rewrite this sql for bigquery engine?
select
left_table.*,x.*
from
data left_table
cross join lateral
(
select string_agg(right_table.session_id,',')
from
data right_table
where left_table.source_ip = right_table.source_ip
and
((right_table.session_start_time >= left_table.session_start_time and right_table.session_start_time <= left_table.session_end_time)
or
(right_table.session_end_time >= left_table.session_start_time and right_table.session_end_time <= left_table.session_end_time))
group by right_table.source_ip
) x
2
Answers
Without lateral joins the "equivalent" is a "correlated subquery" in the select clause, and these are often a performance issue as the correlated subquery is executed row by row though the resultset:
nb: The lateral join is executed in a more efficient manner (as part of the from clause).
You can try this code. In this code CROSS JOIN LATERAL is not used, instead correlated sub-queries are used to achieve the same result.