If you do not enable billing for a project, you automatically work in the
BigQuery sandbox. The BigQuery sandbox lets you learn
BigQuery with a limited set of BigQuery
features at no charge. If you do not plan to use your project beyond this
document, we recommend that you use the BigQuery sandbox.
Grant roles to your user account. Run the following command once for each of the following
IAM roles:roles/serviceusage.serviceUsageAdmin, roles/bigquery.jobUser
Activate your Google Cloud project in Cloud Shell:
gcloudconfigsetprojectPROJECT_ID
ReplacePROJECT_IDwith the project that you selected for
this walkthrough.
The output is similar to the following:
Updated property [core/project].
Query a public dataset
Select one of the following languages:
C#
In Cloud Shell, create a new C# project and file:
dotnetnewconsole-nBigQueryCsharpDemo
The output is similar to the following. Several lines are omitted to
simplify the output.
Welcome to .NET 6.0!
---------------------
SDK Version: 6.0.407
...
The template "Console App" was created successfully.
...
This command creates a C# project that's namedBigQueryCsharpDemoand a file that's namedProgram.cs.
Open the Cloud Shell Editor:
cloudshellworkspaceBigQueryCsharpDemo
To open a terminal in the Cloud Shell Editor, clickOpen Terminal.
Open your project directory:
cdBigQueryCsharpDemo
Install the BigQuery client library for C#:
dotnetaddpackageGoogle.Cloud.BigQuery.V2
The output is similar to the following. Several lines are omitted to
simplify the output.
Determining projects to restore...
Writing /tmp/tmpF7EKSd.tmp
...
info : Writing assets file to disk.
...
Set the variableGOOGLE_PROJECT_IDto the valueGOOGLE_CLOUD_PROJECTand export the variable:
exportGOOGLE_PROJECT_ID=$GOOGLE_CLOUD_PROJECT
ClickOpen Editor.
In theExplorerpane, locate yourBIGQUERYCSHARPDEMOproject.
Click theProgram.csfile to open it.
To create a query against thebigquery-public-data.stackoverflowdataset that returns the
top 10 most viewed Stack Overflow pages and their view counts, replace
the contents of the file with the following code:
usingSystem;usingGoogle.Cloud.BigQuery.V2;namespaceGoogleCloudSamples{publicclassProgram{publicstaticvoidMain(string[]args){stringprojectId=Environment.GetEnvironmentVariable("GOOGLE_PROJECT_ID");varclient=BigQueryClient.Create(projectId);stringquery=@"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";varresult=client.ExecuteQuery(query,parameters:null);Console.Write("\nQuery Results:\n------------\n");foreach(varrowinresult){Console.WriteLine($"{row["url"]}: {row["view_count"]} views");}}}}
ClickOpen Terminal.
In the terminal, run theProgram.csscript. If you are prompted to
authorize Cloud Shell and agree to the terms, clickAuthorize.
In theExplorerpane, locate yourBIGQUERY-GO-QUICKSTARTproject.
Click theapp.gofile to open it.
To create a query against thebigquery-public-data.stackoverflowdataset that returns the
top 10 most viewed Stack Overflow pages and their view counts, copy the
following code into theapp.gofile:
// 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)}}
ClickOpen Terminal.
In the terminal, run theapp.goscript. If you are prompted to
authorize Cloud Shell and agree to the terms, clickAuthorize.
This command creates a Maven project that's namedbigquery-java-quickstart.
The output is similar to the following. Several lines are omitted to
simplify the output.
[INFO] Scanning for projects...
...
[INFO] Building Maven Stub Project (No POM) 1
...
[INFO] BUILD SUCCESS
...
There are many dependency management systems that you can use other than
Maven. For more information, learn how toset up a Java development environmentto use with
client libraries.
Rename theApp.javafile that Maven creates by default:
In theExplorerpane, in yourBIGQUERY-JAVA-QUICKSTARTproject,
clicksrc>main/java/com/google/app>SimpleApp.java.
The file opens.
To create a query against thebigquery-public-data.stackoverflowdataset, leave the
first line of the file (package com.google.app;), and replace the
remaining contents of the file with the following code:
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());}}}
The query returns the top 10 most viewed Stack Overflow pages and
their view counts.
Right-clickSimpleApp.javaand clickRun Java. If you are
prompted to authorize Cloud Shell and agree to the terms, clickAuthorize.
This command creates a Node.js project that's namedbigquery-node-quickstartand a file that's namedapp.js.
Open the Cloud Shell Editor:
cloudshellworkspacebigquery-node-quickstart
To open a terminal in the Cloud Shell Editor, clickOpen Terminal.
Open your project directory:
cdbigquery-node-quickstart
Install the BigQuery client library for Node.js:
npminstall@google-cloud/bigquery
The output is similar to the following:
added 63 packages in 2s
ClickOpen Editor.
In theExplorerpane, locate yourBIGQUERY-NODE-QUICKSTARTproject.
Click theapp.jsfile to open it.
To create a query against thebigquery-public-data.stackoverflowdataset that returns the
top 10 most viewed Stack Overflow pages and their view counts, copy the
following code into theapp.jsfile:
// 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=`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`;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();
ClickOpen Terminal.
In the terminal, run theapp.jsscript. If you are prompted to
authorize Cloud Shell and agree to the terms, clickAuthorize.
This command creates a PHP project that's namedbigquery-php-quickstartand a file that's namedapp.php.
Open the Cloud Shell Editor:
cloudshellworkspacebigquery-php-quickstart
To open a terminal in the Cloud Shell Editor, clickOpen Terminal.
Open your project directory:
cdbigquery-php-quickstart
Install the BigQuery client library for PHP:
composerrequiregoogle/cloud-bigquery
The output is similar to the following. Several lines are omitted to
simplify the output.
Running composer update google/cloud-bigquery
Loading composer repositories with package information
Updating dependencies
...
No security vulnerability advisories found
Using version ^1.24 for google/cloud-bigquery
ClickOpen Editor.
In theExplorerpane, locate yourBIGQUERY-PHP-QUICKSTARTproject.
Click theapp.phpfile to open it.
To create a query against thebigquery-public-data.stackoverflowdataset that returns the
top 10 most viewed Stack Overflow pages and their view counts, copy the
following code into theapp.phpfile:
<?php# ...require __DIR__ . '/vendor/autoload.php';use Google\Cloud\BigQuery\BigQueryClient;$bigQuery = new BigQueryClient();$query = <<<ENDSQLSELECTCONCAT('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');}
ClickOpen Terminal.
In the terminal, run theapp.phpscript. If you are prompted to
authorize Cloud Shell and agree to the terms, clickAuthorize.
In theExplorerpane, locate yourBIGQUERY-PYTHON-QUICKSTARTproject.
Click theapp.pyfile to open it.
To create a query against thebigquery-public-data.stackoverflowdataset that returns the
top 10 most viewed Stack Overflow pages and their view counts, copy the
following code into theapp.pyfile:
fromgoogle.cloudimportbigquerydefquery_stackoverflow()->None:client=bigquery.Client()results=client.query_and_wait("""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""")# Waits for job to complete.forrowinresults:print("{}:{}views".format(row.url,row.view_count))if__name__=="__main__":query_stackoverflow()
ClickOpen Terminal.
In the terminal, run theapp.pyscript. If you are prompted to
authorize Cloud Shell and agree to the terms, clickAuthorize.
This command creates a Ruby project that's namedbigquery-ruby-quickstartand a file that's namedapp.rb.
Open the Cloud Shell Editor:
cloudshellworkspacebigquery-ruby-quickstart
To open a terminal in the Cloud Shell Editor, clickOpen Terminal.
Open your project directory:
cdbigquery-ruby-quickstart
Install the BigQuery client library for Ruby:
geminstallgoogle-cloud-bigquery
The output is similar to the following. Several lines are omitted to
simplify the output.
23 gems installed
ClickOpen Editor.
In theExplorerpane, locate yourBIGQUERY-RUBY-QUICKSTARTproject.
Click theapp.rbfile to open it.
To create a query against thebigquery-public-data.stackoverflowdataset that returns the
top 10 most viewed Stack Overflow pages and their view counts, copy the
following code into theapp.rbfile:
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"end
ClickOpen Terminal.
In the terminal, run theapp.rbscript. If you are prompted to
authorize Cloud Shell and agree to the terms, clickAuthorize.
You have successfully queried a public dataset with the
BigQuery Ruby client library.
Clean up
To avoid incurring charges to your Google Cloud account, either delete
your Google Cloud project, or delete the resources that you created in
this walkthrough.
Delete the project
The easiest way to eliminate billing is to delete the project that you
created for the tutorial.
To delete the project:
In the Google Cloud console, go to theManage resourcespage.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-09-04 UTC."],[[["\u003cp\u003eThis guide demonstrates how to query a public dataset using the BigQuery client libraries in multiple programming languages, including C#, Go, Java, Node.js, PHP, Python, and Ruby.\u003c/p\u003e\n"],["\u003cp\u003eYou can use the Google Cloud console to follow step-by-step instructions for querying datasets using your preferred programming language, with each having its own dedicated tutorial.\u003c/p\u003e\n"],["\u003cp\u003eBefore getting started, it's recommended to either use the BigQuery sandbox at no charge or enable billing for your Google Cloud project, and enabling the BigQuery API is necessary.\u003c/p\u003e\n"],["\u003cp\u003eEach language section walks through creating a project, installing the BigQuery client library, writing code to query the \u003ccode\u003ebigquery-public-data.stackoverflow\u003c/code\u003e dataset for the top 10 most viewed Stack Overflow pages, and running the code in Cloud Shell, providing a full query example.\u003c/p\u003e\n"],["\u003cp\u003eAfter following the guides, either the project or the resources used in the guide should be deleted in order to avoid incurring charges.\u003c/p\u003e\n"]]],[],null,[]]