Create a view

Create a view within a dataset.

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")// createView demonstrates creation of a BigQuery logical view.funccreateView(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()meta:=&bigquery.TableMetadata{// This example shows how to create a view of the shakespeare sample dataset, which// provides word frequency information.  This view restricts the results to only contain// results for works that contain the "king" in the title, e.g. King Lear, King Henry V, etc.ViewQuery:"SELECT word, word_count, corpus, corpus_date FROM `bigquery-public-data.samples.shakespeare` WHERE corpus LIKE '%king%'",}iferr:=client.Dataset(datasetID).Table(tableID).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.TableId;importcom.google.cloud.bigquery.TableInfo;importcom.google.cloud.bigquery.ViewDefinition;// Sample to create a viewpublicclassCreateView{publicstaticvoidmain(String[]args){// TODO(developer): Replace these variables before running the sample.StringdatasetName="MY_DATASET_NAME";StringtableName="MY_TABLE_NAME";StringviewName="MY_VIEW_NAME";Stringquery=String.format("SELECT TimestampField, StringField, BooleanField FROM %s.%s",datasetName,tableName);createView(datasetName,viewName,query);}publicstaticvoidcreateView(StringdatasetName,StringviewName,Stringquery){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,viewName);ViewDefinitionviewDefinition=ViewDefinition.newBuilder(query).setUseLegacySql(false).build();bigquery.create(TableInfo.of(tableId,viewDefinition));System.out.println("View created successfully");}catch(BigQueryExceptione){System.out.println("View 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();asyncfunctioncreateView(){// Creates a new view named "my_shared_view" in "my_dataset"./**   * TODO(developer): Uncomment the following lines before running the sample.   */// const myDatasetId = "my_dataset"// const myTableId = "my_shared_view"// const projectId = "bigquery-public-data";// const sourceDatasetId = "usa_names"// const sourceTableId = "usa_1910_current";constmyDataset=awaitbigquery.dataset(myDatasetId);// For all options, see https://cloud.google.com/bigquery/docs/reference/v2/tables#resourceconstoptions={view:`SELECT name    FROM \`${projectId}.${sourceDatasetId}.${sourceTableId}\`    LIMIT 10`,};// Create a new view in the datasetconst[view]=awaitmyDataset.createTable(myTableId,options);console.log(`View${view.id} created.`);}

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()view_id="my-project.my_dataset.my_view"source_id="my-project.my_dataset.my_table"view=bigquery.Table(view_id)# The source table in this example is created from a CSV file in Google# Cloud Storage located at# `gs://cloud-samples-data/bigquery/us-states/us-states.csv`. It contains# 50 US states, while the view returns only those states with names# starting with the letter 'W'.view.view_query=f"SELECT name, post_abbr FROM `{source_id}` WHERE name LIKE 'W%'"# Make an API request to create the view.view=client.create_table(view)print(f"Created{view.table_type}:{str(view.reference)}")

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="myview"deletion_protection=false # set to "true" in productionview{query="SELECT global_id, faa_identifier, name, latitude, longitude FROM `bigquery-public-data.faa.us_airports`"use_legacy_sql=false}}

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.