Abhay
Abhay

Reputation: 845

Can queries in the bigquery python API use python variables?

I want to run a sql query on multiple tables in a dataset in bigquery. I have the names of these tables in a list in my python script and I want to loop through that list and run the query on every table in the list.

My issue is that I cannot figure out how to structure my query to take python variables as inputs. For example, I have these variables in my script:

# Variables for testing
dataset_id = 'test_dataset'
table_id = 'test_table'

This is how I'm trying to use them in my query object:

query = """
          SELECT *
          FROM """ + dataset_id + '.' + table_id + """
          ORDER BY 1 asc;

    """

This doesn't work and I can't find anything relevant on this online. I'd really appreciate it if you could help me structure this query correctly!

Upvotes: 2

Views: 1589

Answers (1)

Sabri Karagönen
Sabri Karagönen

Reputation: 2365

It should be working. Just to be sure it's working, you can add backticks to the beginning and ending of the table name. Also, by using f-strings in python, you can inject variables in the strings in a more readable way.

query = f"""
          SELECT *
          FROM `{dataset_id}.{table_id}`
          ORDER BY 1 asc;

    """

Upvotes: 4

Related Questions