Query with the BigQuery API Stay organized with collections Save and categorize content based on your preferences.
Create a simple app with BigQuery.
Explore further
For detailed documentation that includes this code sample, see the following:
- BigQuery API Client Libraries
- Get started with authentication
- Query a public dataset with the BigQuery C# client library
- Query a public dataset with the BigQuery client libraries
- Query a public dataset with the BigQuery Go client library
- Query a public dataset with the BigQuery Java client library
- Query a public dataset with the BigQuery Node.js client library
- Query a public dataset with the BigQuery PHP client library
- Query a public dataset with the BigQuery Python client library
- Query a public dataset with the BigQuery Ruby client library
Code sample
C#
Before trying this sample, follow theC# setup instructions in theBigQuery quickstart using client libraries. For more information, see theBigQueryC# API reference documentation.
To authenticate to BigQuery, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.
usingSystem;usingGoogle.Cloud.BigQuery.V2;namespaceGoogleCloudSamples{publicclassProgram{publicstaticvoidMain(string[]args){stringprojectId=Environment.GetEnvironmentVariable("GOOGLE_PROJECT_ID");varclient=BigQueryClient.Create(projectId);stringquery=@"SELECT CONCAT( 'https://stackoverflow.com/questions/', CAST(id as STRING)) as url, view_count FROM `bigquery-public-data.stackoverflow.posts_questions` WHERE tags like '%google-bigquery%' ORDER BY view_count DESC LIMIT 10";varresult=client.ExecuteQuery(query,parameters:null);Console.Write("\nQuery Results:\n------------\n");foreach(varrowinresult){Console.WriteLine($"{row["url"]}: {row["view_count"]} views");}}}}Go
Before trying this sample, follow theGo setup instructions in theBigQuery quickstart using client libraries. For more information, see theBigQueryGo API reference documentation.
To authenticate to BigQuery, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.
// Command simpleapp queries the Stack Overflow public dataset in Google BigQuery.packagemainimport("context""fmt""io""log""os""cloud.google.com/go/bigquery""google.golang.org/api/iterator")funcmain(){projectID:=os.Getenv("GOOGLE_CLOUD_PROJECT")ifprojectID==""{fmt.Println("GOOGLE_CLOUD_PROJECT environment variable must be set.")os.Exit(1)}ctx:=context.Background()client,err:=bigquery.NewClient(ctx,projectID)iferr!=nil{log.Fatalf("bigquery.NewClient: %v",err)}deferclient.Close()rows,err:=query(ctx,client)iferr!=nil{log.Fatal(err)}iferr:=printResults(os.Stdout,rows);err!=nil{log.Fatal(err)}}// query returns a row iterator suitable for reading query results.funcquery(ctxcontext.Context,client*bigquery.Client)(*bigquery.RowIterator,error){query:=client.Query(`SELECTCONCAT('https://stackoverflow.com/questions/',CAST(id as STRING)) as url,view_countFROM `+"`bigquery-public-data.stackoverflow.posts_questions`"+`WHERE tags like '%google-bigquery%'ORDER BY view_count DESCLIMIT 10;`)returnquery.Read(ctx)}typeStackOverflowRowstruct{URLstring`bigquery:"url"`ViewCountint64`bigquery:"view_count"`}// printResults prints results from a query to the Stack Overflow public dataset.funcprintResults(wio.Writer,iter*bigquery.RowIterator)error{for{varrowStackOverflowRowerr:=iter.Next(&row)iferr==iterator.Done{returnnil}iferr!=nil{returnfmt.Errorf("error iterating through results: %w",err)}fmt.Fprintf(w,"url: %s views: %d\n",row.URL,row.ViewCount)}}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.cloud.bigquery.BigQuery;importcom.google.cloud.bigquery.BigQueryException;importcom.google.cloud.bigquery.BigQueryOptions;importcom.google.cloud.bigquery.FieldValueList;importcom.google.cloud.bigquery.Job;importcom.google.cloud.bigquery.JobId;importcom.google.cloud.bigquery.JobInfo;importcom.google.cloud.bigquery.QueryJobConfiguration;importcom.google.cloud.bigquery.TableResult;publicclassSimpleApp{publicstaticvoidmain(String...args)throwsException{// TODO(developer): Replace these variables before running the app.StringprojectId="MY_PROJECT_ID";simpleApp(projectId);}publicstaticvoidsimpleApp(StringprojectId){try{BigQuerybigquery=BigQueryOptions.getDefaultInstance().getService();QueryJobConfigurationqueryConfig=QueryJobConfiguration.newBuilder("SELECT CONCAT('https://stackoverflow.com/questions/', "+"CAST(id as STRING)) as url, view_count "+"FROM `bigquery-public-data.stackoverflow.posts_questions` "+"WHERE tags like '%google-bigquery%' "+"ORDER BY view_count DESC "+"LIMIT 10")// Use standard SQL syntax for queries.// See: https://cloud.google.com/bigquery/sql-reference/.setUseLegacySql(false).build();JobIdjobId=JobId.newBuilder().setProject(projectId).build();JobqueryJob=bigquery.create(JobInfo.newBuilder(queryConfig).setJobId(jobId).build());// Wait for the query to complete.queryJob=queryJob.waitFor();// Check for errorsif(queryJob==null){thrownewRuntimeException("Job no longer exists");}elseif(queryJob.getStatus().getExecutionErrors()!=null &&queryJob.getStatus().getExecutionErrors().size() >0){// TODO(developer): Handle errors here. An error here do not necessarily mean that the job// has completed or was unsuccessful.// For more details: https://cloud.google.com/bigquery/troubleshooting-errorsthrownewRuntimeException("An unhandled error has occurred");}// Get the results.TableResultresult=queryJob.getQueryResults();// Print all pages of the results.for(FieldValueListrow:result.iterateAll()){// String typeStringurl=row.get("url").getStringValue();StringviewCount=row.get("view_count").getStringValue();System.out.printf("%s : %s views\n",url,viewCount);}}catch(BigQueryException|InterruptedExceptione){System.out.println("Simple App failed due to error: \n"+e.toString());}}}Node.js
Before trying this sample, follow theNode.js setup instructions in theBigQuery quickstart using client libraries. For more information, see theBigQueryNode.js API reference documentation.
To authenticate to BigQuery, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.
// Import the Google Cloud client libraryconst{BigQuery}=require('@google-cloud/bigquery');asyncfunctionqueryStackOverflow(){// Queries a public Stack Overflow dataset.// Create a clientconstbigqueryClient=newBigQuery();// The SQL query to runconstsqlQuery=`SELECT CONCAT( 'https://stackoverflow.com/questions/', CAST(id as STRING)) as url, view_count FROM \`bigquery-public-data.stackoverflow.posts_questions\` WHERE tags like '%google-bigquery%' ORDER BY view_count DESC LIMIT 10`;constoptions={query:sqlQuery,// Location must match that of the dataset(s) referenced in the query.location:'US',};// Run the queryconst[rows]=awaitbigqueryClient.query(options);console.log('Query Results:');rows.forEach(row=>{consturl=row['url'];constviewCount=row['view_count'];console.log(`url:${url},${viewCount} views`);});}queryStackOverflow();PHP
Before trying this sample, follow thePHP setup instructions in theBigQuery quickstart using client libraries. For more information, see theBigQueryPHP API reference documentation.
To authenticate to BigQuery, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.
<?php# ...require __DIR__ . '/vendor/autoload.php';use Google\Cloud\BigQuery\BigQueryClient;$bigQuery = new BigQueryClient();$query = <<<ENDSQLSELECT CONCAT( 'https://stackoverflow.com/questions/', CAST(id as STRING)) as url, view_countFROM `bigquery-public-data.stackoverflow.posts_questions`WHERE tags like '%google-bigquery%'ORDER BY view_count DESCLIMIT 10;ENDSQL;$queryJobConfig = $bigQuery->query($query);$queryResults = $bigQuery->runQuery($queryJobConfig);if ($queryResults->isComplete()) { $i = 0; $rows = $queryResults->rows(); foreach ($rows as $row) { printf('--- Row %s ---' . PHP_EOL, ++$i); printf('url: %s, %s views' . PHP_EOL, $row['url'], $row['view_count']); } printf('Found %s row(s)' . PHP_EOL, $i);} else { throw new Exception('The query failed to complete');}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.cloudimportbigquerydefquery_stackoverflow()->None:client=bigquery.Client()results=client.query_and_wait(""" SELECT CONCAT( 'https://stackoverflow.com/questions/', CAST(id as STRING)) as url, view_count FROM `bigquery-public-data.stackoverflow.posts_questions` WHERE tags like '%google-bigquery%' ORDER BY view_count DESC LIMIT 10""")# Waits for job to complete.forrowinresults:print("{} :{} views".format(row.url,row.view_count))if__name__=="__main__":query_stackoverflow()Ruby
Before trying this sample, follow theRuby setup instructions in theBigQuery quickstart using client libraries. For more information, see theBigQueryRuby API reference documentation.
To authenticate to BigQuery, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.
require"google/cloud/bigquery"# This uses Application Default Credentials to authenticate.# @see https://cloud.google.com/bigquery/docs/authentication/getting-startedbigquery=Google::Cloud::Bigquery.newsql="SELECT "\"CONCAT('https://stackoverflow.com/questions/', CAST(id as STRING)) as url, view_count "\"FROM `bigquery-public-data.stackoverflow.posts_questions` "\"WHERE tags like '%google-bigquery%' "\"ORDER BY view_count DESC LIMIT 10"results=bigquery.querysqlresults.eachdo|row|puts"#{row[:url]}:#{row[:view_count]} views"endWhat'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.