Create a table

Create 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""cloud.google.com/go/bigquery")// createTableWithCMEK demonstrates creating a table protected with a customer managed encryption key.funccreateTableWithCMEK(projectID,datasetID,tableIDstring)error{// projectID := "my-project-id"// datasetID := "mydatasetid"// tableID := "mytableid"ctx:=context.Background()client,err:=bigquery.NewClient(ctx,projectID)iferr!=nil{returnfmt.Errorf("bigquery.NewClient: %w",err)}deferclient.Close()tableRef:=client.Dataset(datasetID).Table(tableID)meta:=&bigquery.TableMetadata{EncryptionConfig:&bigquery.EncryptionConfig{// TODO: Replace this key with a key you have created in Cloud KMS.KMSKeyName:"projects/cloud-samples-tests/locations/us/keyRings/test/cryptoKeys/test",},}iferr:=tableRef.Create(ctx,meta);err!=nil{returnerr}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.Field;importcom.google.cloud.bigquery.Schema;importcom.google.cloud.bigquery.StandardSQLTypeName;importcom.google.cloud.bigquery.StandardTableDefinition;importcom.google.cloud.bigquery.TableDefinition;importcom.google.cloud.bigquery.TableId;importcom.google.cloud.bigquery.TableInfo;// Sample to create a cmek tablepublicclassCreateTableCmek{publicstaticvoidmain(String[]args){// TODO(developer): Replace these variables before running the sample.StringdatasetName="MY_DATASET_NAME";StringtableName="MY_TABLE_NAME";StringkmsKeyName="MY_KEY_NAME";Schemaschema=Schema.of(Field.of("stringField",StandardSQLTypeName.STRING),Field.of("booleanField",StandardSQLTypeName.BOOL));// i.e. projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{cryptoKey}EncryptionConfigurationencryption=EncryptionConfiguration.newBuilder().setKmsKeyName(kmsKeyName).build();createTableCmek(datasetName,tableName,schema,encryption);}publicstaticvoidcreateTableCmek(StringdatasetName,StringtableName,Schemaschema,EncryptionConfigurationconfiguration){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();TableIdtableId=TableId.of(datasetName,tableName);TableDefinitiontableDefinition=StandardTableDefinition.of(schema);TableInfotableInfo=TableInfo.newBuilder(tableId,tableDefinition).setEncryptionConfiguration(configuration).build();bigquery.create(tableInfo);System.out.println("Table cmek created successfully");}catch(BigQueryExceptione){System.out.println("Table cmek was not created. \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.cloudimportbigqueryclient=bigquery.Client()# TODO(dev): Change table_id to the full name of the table you want to create.table_id="your-project.your_dataset.your_table_name"# Set the encryption key to use for the table.# TODO: Replace this key with a key you have created in Cloud KMS.kms_key_name="projects/your-project/locations/us/keyRings/test/cryptoKeys/test"table=bigquery.Table(table_id)table.encryption_configuration=bigquery.EncryptionConfiguration(kms_key_name=kms_key_name)table=client.create_table(table)# API requestprint(f"Created{table_id}.")print(f"Key:{table.encryption_configuration.kms_key_name}.")

Terraform

To learn how to apply or remove a Terraform configuration, seeBasic Terraform commands. For more information, see theTerraform provider reference documentation.

resource"google_bigquery_dataset""default"{dataset_id="mydataset"default_partition_expiration_ms=2592000000  # 30 daysdefault_table_expiration_ms=31536000000 # 365 daysdescription="dataset description"location="US"max_time_travel_hours=96 # 4 dayslabels={billing_group="accounting",pii="sensitive"}}resource"google_bigquery_table""default"{dataset_id=google_bigquery_dataset.default.dataset_idtable_id="mytable"deletion_protection=false # set to "true" in productionschema=<<EOF[{"name":"ID","type":"INT64","mode":"NULLABLE","description":"Item ID"},{"name":"Item","type":"STRING","mode":"NULLABLE"}]EOFencryption_configuration{kms_key_name=google_kms_crypto_key.crypto_key.id}depends_on=[google_project_iam_member.service_account_access]}resource"google_kms_crypto_key""crypto_key"{name="example-key"key_ring=google_kms_key_ring.key_ring.id}resource"random_id""default"{byte_length=8}resource"google_kms_key_ring""key_ring"{name="${random_id.default.hex}-example-keyring"location="us"}# Enable the BigQuery service account to encrypt/decrypt Cloud KMS keysdata"google_project""project"{}resource"google_project_iam_member""service_account_access"{project=data.google_project.project.project_idrole="roles/cloudkms.cryptoKeyEncrypterDecrypter"member="serviceAccount:bq-${data.google_project.project.number}@bigquery-encryption.iam.gserviceaccount.com"}

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.