Stay organized with collectionsSave and categorize content based on your preferences.
Query a public dataset with the BigQuery Go client library
Query a public dataset with the BigQuery Go client library
Learn how to:
Activate Cloud Shell in a Google Cloud project.
Open the Cloud Shell Editor.
Prepare files for queries.
Query a public dataset in BigQuery.
Clean up.
Estimated time to complete:
ClickStartto begin.
Activate Cloud Shell in a Google Cloud project
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.
ClickActivate
Cloud Shell.Show
me
To learn how to open the Cloud Shell Editor, clickNext.
To learn how to query a public dataset in BigQuery, clickNext.
Query a public dataset in BigQuery
ClickOpen Editor.
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.
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
If you created a new project to learn about BigQuery and you no
longer need the project,delete it. Be aware
that deleting a project deletes everything in the project and custom project IDs
are lost.
Delete the resources
If you used an existing project, delete thebigquery-go-quickstartfolder
that you created:
[[["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-09 UTC."],[],[],null,["Query a public dataset with the BigQuery Go client library\n\n\nQuery a public dataset with the BigQuery Go client library\n==========================================================\n\nLearn how to:\n\n\u003cbr /\u003e\n\n1. Activate Cloud Shell in a Google Cloud project.\n2. Open the Cloud Shell Editor.\n3. Prepare files for queries.\n4. Query a public dataset in BigQuery.\n5. Clean up.\n\nEstimated time to complete:\n\nClick **Start** to begin.\n\nActivate Cloud Shell in a Google Cloud project\n----------------------------------------------\n\n1.\n\n If you do not enable billing for a project, you automatically work in the\n BigQuery sandbox. The BigQuery sandbox lets you learn\n BigQuery with a limited set of BigQuery\n features at no charge. If you do not plan to use your project beyond this\n document, we recommend that you use the BigQuery sandbox.\n2. \n3. Click **Activate\n Cloud Shell** . Show me\n\nTo learn how to open the Cloud Shell Editor, click **Next**.\n\nOpen the Cloud Shell Editor\n---------------------------\n\n1. In Cloud Shell, create a new Go project and file:\n\n mkdir bigquery-go-quickstart \\\n && touch \\\n bigquery-go-quickstart/app.go\n\n This command creates a Go project that's named `bigquery-go-quickstart`\n and a file that's named `app.go`.\n2. Open the Cloud Shell Editor:\n\n cloudshell workspace bigquery-go-quickstart\n\nTo learn how to prepare files for queries, click **Next**.\n\nPrepare files for queries\n-------------------------\n\n1. To open a terminal in the Cloud Shell Editor, click\n **Open Terminal**.\n\n2. Open your project directory:\n\n cd bigquery-go-quickstart\n\n3. Create a `go.mod` file:\n\n go mod init quickstart\n\n The output is similar to the following: \n\n go: creating new go.mod: module quickstart\n go: to add module requirements and sums:\n go mod tidy\n\n4. Install the BigQuery client library for Go:\n\n go get cloud.google.com/go/bigquery\n\n The output is similar to the following. Several lines are omitted to\n simplify the output. \n\n go: downloading cloud.google.com/go/bigquery v1.49.0\n go: downloading cloud.google.com/go v0.110.0\n ...\n go: added cloud.google.com/go/bigquery v1.49.0\n go: added cloud.google.com/go v0.110.0\n\nTo learn how to query a public dataset in BigQuery, click\n**Next**.\n\nQuery a public dataset in BigQuery\n----------------------------------\n\n1. Click **Open Editor**.\n\n2. In the **Explorer** pane, locate your `BIGQUERY-GO-QUICKSTART`\n project.\n\n3. Click the `app.go` file to open it.\n\n4. To create a query against the\n `bigquery-public-data.stackoverflow` dataset that returns the\n top 10 most viewed Stack Overflow pages and their view counts, copy the\n following code into the `app.go` file:\n\n\n\n // Command simpleapp queries the Stack Overflow public dataset in Google BigQuery.\n package main\n\n import (\n \t\"context\"\n \t\"fmt\"\n \t\"io\"\n \t\"log\"\n \t\"os\"\n\n \t\"cloud.google.com/go/bigquery\"\n \t\"google.golang.org/api/iterator\"\n )\n\n\n func main() {\n \tprojectID := os.Getenv(\"GOOGLE_CLOUD_PROJECT\")\n \tif projectID == \"\" {\n \t\tfmt.Println(\"GOOGLE_CLOUD_PROJECT environment variable must be set.\")\n \t\tos.Exit(1)\n \t}\n\n \tctx := context.Background()\n\n \tclient, err := bigquery.NewClient(ctx, projectID)\n \tif err != nil {\n \t\tlog.Fatalf(\"bigquery.NewClient: %v\", err)\n \t}\n \tdefer client.Close()\n\n \trows, err := query(ctx, client)\n \tif err != nil {\n \t\tlog.Fatal(err)\n \t}\n \tif err := printResults(os.Stdout, rows); err != nil {\n \t\tlog.Fatal(err)\n \t}\n }\n\n // query returns a row iterator suitable for reading query results.\n func query(ctx context.Context, client *bigquery.Client) (*bigquery.https://cloud.google.com/go/docs/reference/cloud.google.com/go/bigquery/latest/index.html#cloud_google_com_go_bigquery_RowIterator, error) {\n\n \tquery := client.Query(\n \t\t`SELECT\n \t\t\tCONCAT(\n \t\t\t\t'https://stackoverflow.com/questions/',\n \t\t\t\tCAST(id as STRING)) as url,\n \t\t\tview_count\n \t\tFROM ` + \"`bigquery-public-data.stackoverflow.posts_questions`\" + `\n \t\tWHERE tags like '%google-bigquery%'\n \t\tORDER BY view_count DESC\n \t\tLIMIT 10;`)\n \treturn query.Read(ctx)\n }\n\n type StackOverflowRow struct {\n \tURL string `bigquery:\"url\"`\n \tViewCount int64 `bigquery:\"view_count\"`\n }\n\n // printResults prints results from a query to the Stack Overflow public dataset.\n func printResults(w io.Writer, iter *bigquery.https://cloud.google.com/go/docs/reference/cloud.google.com/go/bigquery/latest/index.html#cloud_google_com_go_bigquery_RowIterator) error {\n \tfor {\n \t\tvar row StackOverflowRow\n \t\terr := iter.Next(&row)\n \t\tif err == iterator.Done {\n \t\t\treturn nil\n \t\t}\n \t\tif err != nil {\n \t\t\treturn fmt.Errorf(\"error iterating through results: %w\", err)\n \t\t}\n\n \t\tfmt.Fprintf(w, \"url: %s views: %d\\n\", row.URL, row.ViewCount)\n \t}\n }\n\n \u003cbr /\u003e\n\n5. Click **Open Terminal**.\n\n6. In the terminal, run the `app.go` script. If you are prompted to authorize\n Cloud Shell and agree to the terms, click **Authorize**.\n\n go run app.go\n\n The result is similar to the following: \n\n https://stackoverflow.com/questions/35159967 : 170023 views\n https://stackoverflow.com/questions/22879669 : 142581 views\n https://stackoverflow.com/questions/10604135 : 132406 views\n https://stackoverflow.com/questions/44564887 : 128781 views\n https://stackoverflow.com/questions/27060396 : 127008 views\n https://stackoverflow.com/questions/12482637 : 120766 views\n https://stackoverflow.com/questions/20673986 : 115720 views\n https://stackoverflow.com/questions/39109817 : 108368 views\n https://stackoverflow.com/questions/11057219 : 105175 views\n https://stackoverflow.com/questions/43195143 : 101878 views\n\nYou have successfully queried a public dataset with the BigQuery\nGo client library.\n\nTo avoid incurring charges to your account and learn about next steps, click\n**Next**.\n\nNext steps\n----------\n\n\nKeep the resources that you created and do more with BigQuery, or clean up to avoid\nbilling charges.\n\n### Do more with BigQuery\n\n- Learn more about using the [BigQuery Go client library](/go/docs/reference/cloud.google.com/go/bigquery/latest).\n- Learn more about [BigQuery public datasets](/bigquery/public-data).\n- Learn how to [load data into BigQuery](/bigquery/docs/loading-data).\n- Learn more about [querying data in BigQuery](/bigquery/docs/query-overview).\n- Get [updates about BigQuery](/bigquery/docs/release-notes).\n- Learn about [BigQuery pricing](/bigquery/pricing).\n- Learn about [BigQuery quotas and limits](/bigquery/quotas).\n\n### Clean up\n\nTo avoid incurring charges to your Google Cloud account, either delete\nyour Google Cloud project, or delete the resources that you created in\nthis walkthrough.\n\n### Delete the project\n\nIf you created a new project to learn about BigQuery and you no\nlonger need the project,\n[delete it](https://console.cloud.google.com/cloud-resource-manager). Be aware\nthat deleting a project deletes everything in the project and custom project IDs\nare lost.\n\n### Delete the resources\n\nIf you used an existing project, delete the `bigquery-go-quickstart` folder\nthat you created:\n\n1. In Cloud Shell, move up a directory:\n\n cd ..\n\n2. Delete the resources that you created:\n\n rm -R bigquery-go-quickstart\n\n The `-R` flag deletes all assets in a folder."]]