Query script

Run a query script.

Code sample

Java

Before trying this sample, follow theJava setup instructions in theBigQuery quickstart using client libraries. For more information, see theBigQueryJava API reference documentation.

To authenticate to BigQuery, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

importcom.google.api.gax.paging.Page;importcom.google.cloud.bigquery.BigQuery;importcom.google.cloud.bigquery.BigQueryException;importcom.google.cloud.bigquery.BigQueryOptions;importcom.google.cloud.bigquery.Job;importcom.google.cloud.bigquery.JobInfo;importcom.google.cloud.bigquery.QueryJobConfiguration;// Sample to run query script.publicclassQueryScript{publicstaticvoidmain(String[]args){Stringscript="-- Declare a variable to hold names as an array.\n"+"DECLARE top_names ARRAY<STRING>;\n"+"-- Build an array of the top 100 names from the year 2017.\n"+"SET top_names = (\n"+"  SELECT ARRAY_AGG(name ORDER BY number DESC LIMIT 100)\n"+"  FROM `bigquery-public-data`.usa_names.usa_1910_current\n"+"  WHERE year = 2017\n"+");\n"+"-- Which names appear as words in Shakespeare's plays?\n"+"SELECT\n"+"  name AS shakespeare_name\n"+"FROM UNNEST(top_names) AS name\n"+"WHERE name IN (\n"+"  SELECT word\n"+"  FROM `bigquery-public-data`.samples.shakespeare\n"+");";queryScript(script);}publicstaticvoidqueryScript(Stringscript){try{// Initialize client that will be used to send requests. This client only needs to be created// once, and can be reused for multiple requests.BigQuerybigquery=BigQueryOptions.getDefaultInstance().getService();QueryJobConfigurationqueryConfig=QueryJobConfiguration.newBuilder(script).build();JobcreateJob=bigquery.create(JobInfo.of(queryConfig));// Wait for the whole script to finish.JobInfojobInfo=createJob.waitFor();StringparentJobId=jobInfo.getJobId().getJob();// Fetch jobs created by the SQL script.Page<Job>childJobs=bigquery.listJobs(BigQuery.JobListOption.parentJobId(parentJobId));childJobs.iterateAll().forEach(job->System.out.printf("Child Job Id: ",job.getJobId().getJob()));System.out.println("Query script performed successfully.");}catch(BigQueryException|InterruptedExceptione){System.out.println("Query not performed \n"+e.toString());}}}

Python

Before trying this sample, follow thePython setup instructions in theBigQuery quickstart using client libraries. For more information, see theBigQueryPython API reference documentation.

To authenticate to BigQuery, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

fromgoogle.cloudimportbigquery# Construct a BigQuery client object.client=bigquery.Client()# Run a SQL script.sql_script="""-- Declare a variable to hold names as an array.DECLARE top_names ARRAY<STRING>;-- Build an array of the top 100 names from the year 2017.SET top_names = (SELECT ARRAY_AGG(name ORDER BY number DESC LIMIT 100)FROM `bigquery-public-data.usa_names.usa_1910_2013`WHERE year = 2000);-- Which names appear as words in Shakespeare's plays?SELECTname AS shakespeare_nameFROM UNNEST(top_names) AS nameWHERE name IN (SELECT wordFROM `bigquery-public-data.samples.shakespeare`);"""parent_job=client.query(sql_script)# Wait for the whole script to finish.rows_iterable=parent_job.result()print("Script created{} child jobs.".format(parent_job.num_child_jobs))# Fetch result rows for the final sub-job in the script.rows=list(rows_iterable)print("{} of the top 100 names from year 2000 also appear in Shakespeare's works.".format(len(rows)))# Fetch jobs created by the SQL script.child_jobs_iterable=client.list_jobs(parent_job=parent_job)forchild_jobinchild_jobs_iterable:child_rows=list(child_job.result())print("Child job with ID{} produced{} row(s).".format(child_job.job_id,len(child_rows)))

What's next

To search and filter code samples for other Google Cloud products, see theGoogle Cloud sample browser.

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.