Create table with schema

Create a table with a schema.

Explore further

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

Code sample

C#

Before trying this sample, follow theC# setup instructions in theBigQuery quickstart using client libraries. For more information, see theBigQueryC# API reference documentation.

To authenticate to BigQuery, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

usingGoogle.Cloud.BigQuery.V2;publicclassBigQueryCreateTable{publicBigQueryTableCreateTable(stringprojectId="your-project-id",stringdatasetId="your_dataset_id"){BigQueryClientclient=BigQueryClient.Create(projectId);vardataset=client.GetDataset(datasetId);// Create schema for new table.varschema=newTableSchemaBuilder{{"full_name",BigQueryDbType.String},{"age",BigQueryDbType.Int64}}.Build();// Create the tablereturndataset.CreateTable(tableId:"your_table_id",schema:schema);}}

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""time""cloud.google.com/go/bigquery")// createTableExplicitSchema demonstrates creating a new BigQuery table and specifying a schema.funccreateTableExplicitSchema(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()sampleSchema:=bigquery.Schema{{Name:"full_name",Type:bigquery.StringFieldType},{Name:"age",Type:bigquery.IntegerFieldType},}metaData:=&bigquery.TableMetadata{Schema:sampleSchema,ExpirationTime:time.Now().AddDate(1,0,0),// Table will be automatically deleted in 1 year.}tableRef:=client.Dataset(datasetID).Table(tableID)iferr:=tableRef.Create(ctx,metaData);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.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;publicclassCreateTable{publicstaticvoidmain(String[]args){// TODO(developer): Replace these variables before running the sample.StringdatasetName="MY_DATASET_NAME";StringtableName="MY_TABLE_NAME";Schemaschema=Schema.of(Field.of("stringField",StandardSQLTypeName.STRING),Field.of("booleanField",StandardSQLTypeName.BOOL));createTable(datasetName,tableName,schema);}publicstaticvoidcreateTable(StringdatasetName,StringtableName,Schemaschema){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).build();bigquery.create(tableInfo);System.out.println("Table created successfully");}catch(BigQueryExceptione){System.out.println("Table was not created. \n"+e.toString());}}}

Node.js

Before trying this sample, follow theNode.js setup instructions in theBigQuery quickstart using client libraries. For more information, see theBigQueryNode.js API reference documentation.

To authenticate to BigQuery, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

// Import the Google Cloud client library and create a clientconst{BigQuery}=require('@google-cloud/bigquery');constbigquery=newBigQuery();asyncfunctioncreateTable(){// Creates a new table named "my_table" in "my_dataset"./**   * TODO(developer): Uncomment the following lines before running the sample.   */// const datasetId = "my_dataset";// const tableId = "my_table";// const schema = 'Name:string, Age:integer, Weight:float, IsMagic:boolean';// For all options, see https://cloud.google.com/bigquery/docs/reference/v2/tables#resourceconstoptions={schema:schema,location:'US',};// Create a new table in the datasetconst[table]=awaitbigquery.dataset(datasetId).createTable(tableId,options);console.log(`Table${table.id} created.`);}

PHP

Before trying this sample, follow thePHP setup instructions in theBigQuery quickstart using client libraries. For more information, see theBigQueryPHP API reference documentation.

To authenticate to BigQuery, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

use Google\Cloud\BigQuery\BigQueryClient;/** * Creates a table with the given ID and Schema * * @param string $projectId The project Id of your Google Cloud Project. * @param string $datasetId The BigQuery dataset ID. * @param string $tableId The BigQuery table ID. * @param string $fields Json Encoded string of schema of the table. For eg, *    $fields = json_encode([ *     [ *         'name' => 'field1', *         'type' => 'string', *         'mode' => 'required' *     ], *     [ *         'name' => 'field2', *         'type' => 'integer' *     ], *    ]); */function create_table(    string $projectId,    string $datasetId,    string $tableId,    string $fields): void {    $bigQuery = new BigQueryClient([      'projectId' => $projectId,    ]);    $dataset = $bigQuery->dataset($datasetId);    $fields = json_decode($fields);    $schema = ['fields' => $fields];    $table = $dataset->createTable($tableId, ['schema' => $schema]);    printf('Created table %s' . PHP_EOL, $tableId);}

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 table to create.# table_id = "your-project.your_dataset.your_table_name"schema=[bigquery.SchemaField("full_name","STRING",mode="REQUIRED"),bigquery.SchemaField("age","INTEGER",mode="REQUIRED"),]table=bigquery.Table(table_id,schema=schema)table=client.create_table(table)# Make an API request.print("Created table{}.{}.{}".format(table.project,table.dataset_id,table.table_id))

Ruby

Before trying this sample, follow theRuby setup instructions in theBigQuery quickstart using client libraries. For more information, see theBigQueryRuby API reference documentation.

To authenticate to BigQuery, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

require"google/cloud/bigquery"defcreate_tabledataset_id="my_dataset"bigquery=Google::Cloud::Bigquery.newdataset=bigquery.datasetdataset_idtable_id="my_table"table=dataset.create_tabletable_iddo|updater|updater.string"full_name",mode::requiredupdater.integer"age",mode::requiredendputs"Created table:#{table_id}"end

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"}]EOF}

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.