Save query results
Stay organized with collections
Save and categorize content based on your preferences.
Query saves results to a permanent table.
Explore further
For detailed documentation that includes this code sample, see the following:
Code sample
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License
, and code samples are licensed under the Apache 2.0 License
. For details, see the Google Developers Site Policies
. Java is a registered trademark of Oracle and/or its affiliates.
[[["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"]],[],[[["\u003cp\u003eThis page demonstrates how to save the results of a BigQuery query to a permanent table, using examples in Go, Java, Node.js, and Python.\u003c/p\u003e\n"],["\u003cp\u003eThe code samples provided show how to configure the query to specify a destination table where the results will be stored.\u003c/p\u003e\n"],["\u003cp\u003eEach language example includes instructions on how to authenticate to BigQuery and set up the respective client library environments, with links to quickstart guides and API documentation.\u003c/p\u003e\n"],["\u003cp\u003eThe provided examples use different approaches for setting the destination table, either by using \u003ccode\u003eQueryConfig\u003c/code\u003e object in Go and Java or direct specification in Node.js and Python.\u003c/p\u003e\n"],["\u003cp\u003eThe query used in the examples differs by language, showing how the same result can be obtained with the languages available.\u003c/p\u003e\n"]]],[],null,["Query saves results to a permanent table.\n\nExplore further\n\n\nFor detailed documentation that includes this code sample, see the following:\n\n- [Create and use tables](/bigquery/docs/tables)\n- [Writing query results](/bigquery/docs/writing-results)\n\nCode sample \n\nGo\n\n\nBefore trying this sample, follow the Go setup instructions in the\n[BigQuery quickstart using\nclient libraries](/bigquery/docs/quickstarts/quickstart-client-libraries).\n\n\nFor more information, see the\n[BigQuery Go API\nreference documentation](https://godoc.org/cloud.google.com/go/bigquery).\n\n\nTo authenticate to BigQuery, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for client libraries](/bigquery/docs/authentication#client-libs).\n\n import (\n \t\"context\"\n \t\"fmt\"\n \t\"io\"\n\n \t\"cloud.google.com/go/bigquery\"\n \t\"google.golang.org/api/iterator\"\n )\n\n // queryWithDestination demonstrates saving the results of a query to a specific table by setting the destination\n // via the API properties.\n func queryWithDestination(w io.Writer, projectID, destDatasetID, destTableID string) error {\n \t// projectID := \"my-project-id\"\n \t// datasetID := \"mydataset\"\n \t// tableID := \"mytable\"\n \tctx := context.Background()\n \tclient, err := bigquery.NewClient(ctx, projectID)\n \tif err != nil {\n \t\treturn fmt.Errorf(\"bigquery.NewClient: %w\", err)\n \t}\n \tdefer client.Close()\n\n \tq := client.Query(\"SELECT 17 as my_col\")\n \tq.Location = \"US\" // Location must match the dataset(s) referenced in query.\n \tq.QueryConfig.Dst = client.Dataset(destDatasetID).Table(destTableID)\n \t// Run the query and process the returned row iterator.\n \tit, err := q.Read(ctx)\n \tif err != nil {\n \t\treturn fmt.Errorf(\"query.Read(): %w\", err)\n \t}\n \tfor {\n \t\tvar row []bigquery.Value\n \t\terr := it.Next(&row)\n \t\tif err == iterator.Done {\n \t\t\tbreak\n \t\t}\n \t\tif err != nil {\n \t\t\treturn err\n \t\t}\n \t\tfmt.Fprintln(w, row)\n \t}\n \treturn nil\n }\n\nJava\n\n\nBefore trying this sample, follow the Java setup instructions in the\n[BigQuery quickstart using\nclient libraries](/bigquery/docs/quickstarts/quickstart-client-libraries).\n\n\nFor more information, see the\n[BigQuery Java API\nreference documentation](/java/docs/reference/google-cloud-bigquery/latest/overview).\n\n\nTo authenticate to BigQuery, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for client libraries](/bigquery/docs/authentication#client-libs).\n\n import com.google.cloud.bigquery.BigQuery;\n import com.google.cloud.bigquery.BigQueryException;\n import com.google.cloud.bigquery.BigQueryOptions;\n import com.google.cloud.bigquery.QueryJobConfiguration;\n import com.google.cloud.bigquery.TableId;\n\n public class SaveQueryToTable {\n\n public static void main(String[] args) {\n // TODO(developer): Replace these variables before running the sample.\n String query = \"SELECT corpus FROM `bigquery-public-data.samples.shakespeare` GROUP BY corpus;\";\n String destinationTable = \"MY_TABLE\";\n String destinationDataset = \"MY_DATASET\";\n\n saveQueryToTable(destinationDataset, destinationTable, query);\n }\n\n public static void saveQueryToTable(\n String destinationDataset, String destinationTableId, String query) {\n try {\n // Initialize client that will be used to send requests. This client only needs to be created\n // once, and can be reused for multiple requests.\n BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();\n\n // Identify the destination table\n TableId destinationTable = TableId.of(destinationDataset, destinationTableId);\n\n // Build the query job\n QueryJobConfiguration queryConfig =\n QueryJobConfiguration.newBuilder(query).setDestinationTable(destinationTable).build();\n\n // Execute the query.\n bigquery.query(queryConfig);\n\n // The results are now saved in the destination table.\n\n System.out.println(\"Saved query ran successfully\");\n } catch (BigQueryException | InterruptedException e) {\n System.out.println(\"Saved query did not run \\n\" + e.toString());\n }\n }\n }\n\nNode.js\n\n\nBefore trying this sample, follow the Node.js setup instructions in the\n[BigQuery quickstart using\nclient libraries](/bigquery/docs/quickstarts/quickstart-client-libraries).\n\n\nFor more information, see the\n[BigQuery Node.js API\nreference documentation](https://googleapis.dev/nodejs/bigquery/latest/index.html).\n\n\nTo authenticate to BigQuery, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for client libraries](/bigquery/docs/authentication#client-libs).\n\n // Import the Google Cloud client library\n const {BigQuery} = require('@google-cloud/bigquery');\n const bigquery = new BigQuery();\n\n async function queryDestinationTable() {\n // Queries the U.S. given names dataset for the state of Texas\n // and saves results to permanent table.\n\n /**\n * TODO(developer): Uncomment the following lines before running the sample.\n */\n // const datasetId = 'my_dataset';\n // const tableId = 'my_table';\n\n // Create destination table reference\n const dataset = bigquery.dataset(datasetId);\n const destinationTable = dataset.table(tableId);\n\n const query = `SELECT name\n FROM \\`bigquery-public-data.usa_names.usa_1910_2013\\`\n WHERE state = 'TX'\n LIMIT 100`;\n\n // For all options, see https://cloud.google.com/bigquery/docs/reference/v2/tables#resource\n const options = {\n query: query,\n // Location must match that of the dataset(s) referenced in the query.\n location: 'US',\n destination: destinationTable,\n };\n\n // Run the query as a job\n const [job] = await bigquery.createQueryJob(options);\n\n console.log(`Job ${job.id} started.`);\n console.log(`Query results loaded to table ${destinationTable.id}`);\n }\n\nPython\n\n\nBefore trying this sample, follow the Python setup instructions in the\n[BigQuery quickstart using\nclient libraries](/bigquery/docs/quickstarts/quickstart-client-libraries).\n\n\nFor more information, see the\n[BigQuery Python API\nreference documentation](/python/docs/reference/bigquery/latest).\n\n\nTo authenticate to BigQuery, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for client libraries](/bigquery/docs/authentication#client-libs).\n\n from google.cloud import bigquery\n\n # Construct a BigQuery client object.\n client = bigquery.Client()\n\n # TODO(developer): Set table_id to the ID of the destination table.\n # table_id = \"your-project.your_dataset.your_table_name\"\n\n job_config = bigquery.QueryJobConfig(destination=table_id)\n\n sql = \"\"\"\n SELECT corpus\n FROM `bigquery-public-data.samples.shakespeare`\n GROUP BY corpus;\n \"\"\"\n\n # Start the query, passing in the extra configuration.\n client.query_and_wait(\n sql, job_config=job_config\n ) # Make an API request and wait for the query to finish.\n\n print(\"Query results loaded to the table {}\".format(table_id))\n\nWhat's next\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=bigquery)."]]