6

I have a simple query that runs successfully, but when I introduce a variable into the query, I am unable to save a view using that query. For example:

SELECT * FROM mytable WHERE color = 'red';

This query runs fine. Then:

DECLARE color STRING DEFAULT 'red';
SELECT * FROM mytable WHERE color = color;

This query also runs fine. Then in the BigQuery UI I click to "Save view", but I get an error saying Unexpected keyword DECLARE. Why is that?

3
  • Views are static, so I'm not sure why you want to use a variable in a view (as Gordon points out, this is not possible) but a stored procedure might be more in line with what you are trying to do: cloud.google.com/blog/products/data-analytics/… Commented Jan 15, 2020 at 21:08
  • 1
    @NathanGriffiths the query I gave is just an example. In reality I need to reference the color red in a few places throughout the query, so I thought using a variable would allow me to edit it in one place in case it ever needs to change. Commented Jan 15, 2020 at 21:11
  • If you think the value of color might change over time then a better approach could be to create a stored procedure that accepts color as a parameter and then executes your query. Commented Jan 16, 2020 at 5:01

2 Answers 2

4

As explained in the documentation:

BigQuery views are subject to the following limitations:

  • You cannot reference query parameters in views.

What you want to do is not allowed. A view is limited to a single SELECT statement.

Sign up to request clarification or add additional context in comments.

Comments

0

If you're interested in using a variable more as a named constant than something you expect to be provided dynamically via query parameters, you do have a couple options, even within a view:

WITH constants AS (
  SELECT
    'red' AS color
)
SELECT *
FROM mytable
WHERE fillColor = (select color from constants);

... or, more succinctly (but using a more arcane cross-join syntax):

WITH constants AS (
  SELECT
    'red' AS color
)
SELECT *
FROM mytable, constants
WHERE fillColor = color;

I've found this kind of thing useful in date-snapshotted data warehouses, for example:

WITH constants AS (
  SELECT
    DATE_SUB(CURRENT_DATE("America/Los_Angeles"), INTERVAL 1 DAY) AS latest_ds
)
SELECT *
FROM modelSnapshots, constants
WHERE ds = latest_ds; 

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.