Create an integer-range partitioned table

Create a new integer-range partitioned table in an existing dataset.

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.Apis.Bigquery.v2.Data;usingGoogle.Cloud.BigQuery.V2;publicclassBigQueryCreateTableRangePartitioned{publicBigQueryTableCreateTable(stringprojectId,stringdatasetId,stringtableId){BigQueryClientclient=BigQueryClient.Create(projectId);vardataset=client.GetDataset(datasetId);// Note: The field must be a top- level, NULLABLE/REQUIRED field.// The only supported type is INTEGER/INT64.varpartitioning=newRangePartitioning{Field="integerField",Range=newRangePartitioning.RangeData{Start=1,Interval=2,End=10}};varschema=newTableSchemaBuilder{{"integerField",BigQueryDbType.Int64},{"stringField",BigQueryDbType.String},{"booleanField",BigQueryDbType.Bool},{"dateField",BigQueryDbType.Date}}.Build();vartable=newTable{RangePartitioning=partitioning,Schema=schema};returndataset.CreateTable(tableId,table);}}

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")// createTableRangeParitioned demonstrates creating a table and specifying a// range partitioning configuration.funccreateTableRangePartitioned(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:"city",Type:bigquery.StringFieldType},{Name:"zipcode",Type:bigquery.IntegerFieldType},}metadata:=&bigquery.TableMetadata{RangePartitioning:&bigquery.RangePartitioning{Field:"zipcode",Range:&bigquery.RangePartitioningRange{Start:0,End:100000,Interval:10,},},Schema:sampleSchema,}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.RangePartitioning;importcom.google.cloud.bigquery.Schema;importcom.google.cloud.bigquery.StandardSQLTypeName;importcom.google.cloud.bigquery.StandardTableDefinition;importcom.google.cloud.bigquery.TableId;importcom.google.cloud.bigquery.TableInfo;// Sample to create a range partitioned tablepublicclassCreateRangePartitionedTable{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("integerField",StandardSQLTypeName.INT64),Field.of("stringField",StandardSQLTypeName.STRING),Field.of("booleanField",StandardSQLTypeName.BOOL),Field.of("dateField",StandardSQLTypeName.DATE));createRangePartitionedTable(datasetName,tableName,schema);}publicstaticvoidcreateRangePartitionedTable(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);// Note: The field must be a top- level, NULLABLE/REQUIRED field.// The only supported type is INTEGER/INT64RangePartitioningpartitioning=RangePartitioning.newBuilder().setField("integerField").setRange(RangePartitioning.Range.newBuilder().setStart(1L).setInterval(2L).setEnd(10L).build()).build();StandardTableDefinitiontableDefinition=StandardTableDefinition.newBuilder().setSchema(schema).setRangePartitioning(partitioning).build();TableInfotableInfo=TableInfo.newBuilder(tableId,tableDefinition).build();bigquery.create(tableInfo);System.out.println("Range partitioned table created successfully");}catch(BigQueryExceptione){System.out.println("Range partitioned 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 libraryconst{BigQuery}=require('@google-cloud/bigquery');constbigquery=newBigQuery();asyncfunctioncreateTableRangePartitioned(){// Creates a new integer range partitioned 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";constschema=[{name:'fullName',type:'STRING'},{name:'city',type:'STRING'},{name:'zipcode',type:'INTEGER'},];// To use integer range partitioning, select a top-level REQUIRED or// NULLABLE column with INTEGER / INT64 data type. Values that are// outside of the range of the table will go into the UNPARTITIONED// partition. Null values will be in the NULL partition.constrangePartition={field:'zipcode',range:{start:0,end:100000,interval:10,},};// For all options, see https://cloud.google.com/bigquery/docs/reference/v2/tables#resourceconstoptions={schema:schema,rangePartitioning:rangePartition,};// Create a new table in the datasetconst[table]=awaitbigquery.dataset(datasetId).createTable(tableId,options);console.log(`Table${table.id} created with integer range partitioning: `);console.log(table.metadata.rangePartitioning);}

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"),bigquery.SchemaField("city","STRING"),bigquery.SchemaField("zipcode","INTEGER"),]table=bigquery.Table(table_id,schema=schema)table.range_partitioning=bigquery.RangePartitioning(# To use integer range partitioning, select a top-level REQUIRED /# NULLABLE column with INTEGER / INT64 data type.field="zipcode",range_=bigquery.PartitionRange(start=0,end=100000,interval=10),)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"### Creates a table with range partitioning.## @param dataset_id [String] The ID of the dataset to create the table in.# @param table_id   [String] The ID of the table to create.defcreate_range_partitioned_tabledataset_id,table_idbigquery=Google::Cloud::Bigquery.newdataset=bigquery.datasetdataset_idtable=dataset.create_tabletable_iddo|t|t.schemado|s|s.integer"integerField",mode::requireds.string"stringField",mode::nullables.boolean"booleanField",mode::nullables.date"dateField",mode::nullableendt.range_partitioning_field="integerField"t.range_partitioning_start=1t.range_partitioning_interval=2t.range_partitioning_end=10endputs"Created range-partitioned table:#{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 productionrange_partitioning{field="ID"range{start=0end=1000interval=10}}require_partition_filter=trueschema=<<EOF[{"name":"ID","type":"INT64","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.