Query a table

Query a table with customer-managed encryption keys.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

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.

import("context""fmt""io""cloud.google.com/go/bigquery""google.golang.org/api/iterator")// queryWithDestinationCMEK demonstrates saving query results to a destination table and protecting those results// by specifying a customer managed encryption key.funcqueryWithDestinationCMEK(wio.Writer,projectID,dstDatasetID,dstTableIDstring)error{// projectID := "my-project-id"// datasetID := "mydataset"// tableID := "mytable"ctx:=context.Background()client,err:=bigquery.NewClient(ctx,projectID)iferr!=nil{returnfmt.Errorf("bigquery.NewClient: %w",err)}deferclient.Close()q:=client.Query("SELECT 17 as my_col")q.Location="US"// Location must match the dataset(s) referenced in query.q.QueryConfig.Dst=client.Dataset(dstDatasetID).Table(dstTableID)q.DestinationEncryptionConfig=&bigquery.EncryptionConfig{// TODO: Replace this key with a key you have created in Cloud KMS.KMSKeyName:"projects/cloud-samples-tests/locations/us-central1/keyRings/test/cryptoKeys/test",}// Run the query and process the returned row iterator.it,err:=q.Read(ctx)iferr!=nil{returnfmt.Errorf("query.Read(): %w",err)}for{varrow[]bigquery.Valueerr:=it.Next(&row)iferr==iterator.Done{break}iferr!=nil{returnerr}fmt.Fprintln(w,row)}returnnil}

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.EncryptionConfiguration;importcom.google.cloud.bigquery.QueryJobConfiguration;importcom.google.cloud.bigquery.TableResult;// Sample to query on destination table with encryption keypublicclassQueryDestinationTableCmek{publicstaticvoidmain(String[]args){// TODO(developer): Replace these variables before running the sample.StringdatasetName="MY_DATASET_NAME";StringtableName="MY_TABLE_NAME";StringkmsKeyName="MY_KMS_KEY_NAME";Stringquery=String.format("SELECT stringField, booleanField FROM %s.%s",datasetName,tableName);EncryptionConfigurationencryption=EncryptionConfiguration.newBuilder().setKmsKeyName(kmsKeyName).build();queryDestinationTableCmek(query,encryption);}publicstaticvoidqueryDestinationTableCmek(Stringquery,EncryptionConfigurationencryption){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();QueryJobConfigurationconfig=QueryJobConfiguration.newBuilder(query)// Set the encryption key to use for the destination..setDestinationEncryptionConfiguration(encryption).build();TableResultresults=bigquery.query(config);results.iterateAll().forEach(row->row.forEach(val->System.out.printf("%s,",val.toString())));System.out.println("Query performed successfully with encryption key.");}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()# TODO(developer): Set table_id to the ID of the destination table.# table_id = "your-project.your_dataset.your_table_name"# Set the encryption key to use for the destination.# TODO(developer): Replace this key with a key you have created in KMS.# kms_key_name = "projects/{}/locations/{}/keyRings/{}/cryptoKeys/{}".format(#     your-project, location, your-ring, your-key# )job_config=bigquery.QueryJobConfig(destination=table_id,destination_encryption_configuration=bigquery.EncryptionConfiguration(kms_key_name=kms_key_name),)# Start the query, passing in the extra configuration.query_job=client.query("SELECT 17 AS my_col;",job_config=job_config)# Make an API request.query_job.result()# Wait for the job to complete.table=client.get_table(table_id)# Make an API request.iftable.encryption_configuration.kms_key_name==kms_key_name:print("The destination table is written using the encryption configuration")

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.