0

Is there a way to have SQL scripts within a subquery ?

For example:

select col_1, col_2, count(*) from (
Declare max_radius INT64;
set max_radius = 250;

select * from my_table
where radius <  max_radius
)
group by col_1,col_2

In my case it is not possible to move the variable declaration outside of the subquery. Thanks !

1 Answer 1

1

For this particular example, you could use a CTE to define the parameter values:

with params as (
      select 250 as max_radius
     )
select t.col_1, t.col_2, count(*)
from params p cross join
     my_table t
where t.radius < p.max_radius
group by t.col_1, t.col_2;
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, this was my first though but if my_table is huge (and in reality it is) the cross join will have a very poor performance because it will duplicate the params for each row in mytable. And I wanted to workaround that problem by using a variable.
@Yairh . . . The cross join should be trivial because there is only one row.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.