9

How can I declare a list type variable in BigQuery so that I can use it in a where clause? I have this code

WITH
  subquery AS (
  SELECT
    1 AS col1
  UNION ALL
  SELECT
    2 AS col1
  UNION ALL
  SELECT
    3 AS col1 )

SELECT
  col1
FROM
  subquery
WHERE
  col1 IN (1, 2)

instead I would like to get to the point with the variable in the query

DECLARE list ARRAY;
SET list = (1,2);

WITH
  subquery AS (
  SELECT
    1 AS col1
  UNION ALL
  SELECT
    2 AS col1
  UNION ALL
  SELECT
    3 AS col1 )

SELECT
  col1
FROM
  subquery
WHERE
  col1 IN list

I have tried DECLARE list STRUCT [less than] int64,int64 [greater than] which it doesn't accept

3 Answers 3

15

Try the following code:

DECLARE list ARRAY <INT64>;
SET list = [1,2];

WITH
  subquery AS (
  SELECT
    1 AS col1
  UNION ALL
  SELECT
    2 AS col1
  UNION ALL
  SELECT
    3 AS col1 )

SELECT
  col1
FROM
  subquery
WHERE
  col1 IN UNNEST(list)
Sign up to request clarification or add additional context in comments.

2 Comments

Yay thank you. I struggle to understand arrays and structs. Any good resources?
You can find useful information about it in the link bellow cloud.google.com/bigquery/docs/reference/standard-sql/…
5

You can DECLARE an array and assign it values in one go, without using SET. Example:

DECLARE myArray ARRAY <STRING> DEFAULT ["FIRST", "SECOND", "THIRD"];

SELECT myValues
  FROM UNNEST(myArray) AS myValues

You may prefer a subquery, using WITH. Example:

WITH myArray AS (
  SELECT *
    FROM UNNEST(["FIRST", "SECOND", "THIRD"]) AS myValues
)
SELECT myValues
  FROM myArray

Both queries will provide the same result:

+----------+
| myValues |
+----------+
| FIRST    |
| SECOND   | 
| THIRD    |
+----------+

Comments

4

The following syntax also seems to work, if you really want to use DECLARE with a STRUCT type, or for other people who find this post:

DECLARE foo DEFAULT (SELECT AS STRUCT 2, 2, 2, 2);

Comments

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.