Updating view properties

This document describes how to update view properties or metadata. After creating a view, you can update the following view properties:

Required permissions

At a minimum, to update a view, you must be granted bigquery.tables.update and bigquery.tables.get permissions. If you are updating the view's SQL query, you must also have permissions to query any tables referenced by the view's SQL query.

The following predefined Cloud IAM roles include bigquery.tables.update and bigquery.tables.get permissions:

  • bigquery.dataEditor
  • bigquery.dataOwner
  • bigquery.admin

In addition, if a user has bigquery.datasets.create permissions, when that user creates a dataset, they are granted bigquery.dataOwner access to it. bigquery.dataOwner access gives the user the ability to update tables and views in the dataset.

For more information on Cloud IAM roles and permissions in BigQuery, see Predefined roles and permissions.

Updating a view's SQL query

You can update the SQL query used to define a view by:

  • Using the GCP Console or the classic BigQuery web UI
  • Using the command-line tool's bq update command
  • Calling the tables.patch API method
  • Using the client libraries

You can change the SQL dialect from legacy SQL to standard SQL in the CLI or API. You cannot update a legacy SQL view to standard SQL in the GCP Console or the classic BigQuery web UI.

To update a view's SQL query:

Console

  1. In the Resources panel, expand your project and dataset and select the view.

  2. Click the Details tab.

    View details

  3. Above the Query box, click the Edit query button. Click Open in the dialog that appears.

    Edit query

  4. Edit the SQL query in the Query editor box and then click Save view.

    Save view

  5. Make sure all the fields are correct in the Save view dialog and then click Save.

Classic UI

  1. Select the view.

  2. In the View Details panel, click Details.

  3. Below the Query box, click Edit Query.

  4. Edit the SQL query in the Query box and then click Save View.

    Update view

CLI

Issue the bq update command with the --view flag. To use standard SQL or to update the query dialect from legacy SQL to standard SQL, include the --use_legacy_sql flag and set it to false.

If your query references external user-defined function resources stored in Google Cloud Storage or in local files, use the --view_udf_resource flag to specify those resources. The --view_udf_resource flag is not demonstrated here. For more information on using UDFs, see Standard SQL User-Defined Functions.

If you are updating a view in a project other than your default project, add the project ID to the dataset name in the following format: project_id:dataset.

bq update \
--use_legacy_sql=false \
--view_udf_resource=path_to_file \
--view='query' \
project_id:dataset.view

Where:

  • path_to_file is the URI or local filesystem path to a code file to be loaded and evaluated immediately as a user-defined function resource used by the view. Repeat the flag to specify multiple files.
  • query is a valid standard SQL query.
  • project_id is your project ID.
  • dataset is a dataset that contains the view.
  • view is the name of the view you want to update.

Examples:

Enter the following command to update the SQL query for a view named myview in mydataset. mydataset is in your default project. The example query used to update the view queries data from the USA Name Data public dataset.

bq update \
--use_legacy_sql=false \
--view \
'SELECT
  name,
  number
FROM
  `bigquery-public-data.usa_names.usa_1910_current`
WHERE
  gender = "M"
ORDER BY
  number DESC' \
mydataset.myview

Enter the following command to update the SQL query for a view named myview in mydataset. mydataset is in myotherproject, not your default project. The example query used to update the view queries data from the USA Name Data public dataset.

bq update \
--use_legacy_sql=false \
--view \
'SELECT
  name,
  number
FROM
  `bigquery-public-data.usa_names.usa_1910_current`
WHERE
  gender = "M"
ORDER BY
  number DESC' \
myotherproject:mydataset.myview

API

You can update a view by calling the tables.patch method with a table resource that contains an updated view property. Because the tables.update method replaces the entire table resource, the tables.patch method is preferred.

Go

Before trying this sample, follow the Go setup instructions in the BigQuery Quickstart Using Client Libraries . For more information, see the BigQuery Go API reference documentation .

// To run this sample, you will need to create (or reuse) a context and
// an instance of the bigquery client.  For example:
// import "cloud.google.com/go/bigquery"
// ctx := context.Background()
// client, err := bigquery.NewClient(ctx, "your-project-id")
view := client.Dataset(datasetID).Table(viewID)
meta, err := view.Metadata(ctx)
if err != nil {
	return err
}

newMeta := bigquery.TableMetadataToUpdate{
	// This example updates a view into the shakespeare dataset to exclude works named after kings.
	ViewQuery: "SELECT word, word_count, corpus, corpus_date FROM `bigquery-public-data.samples.shakespeare` WHERE corpus NOT LIKE '%king%'",
}

if _, err := view.Update(ctx, newMeta, meta.ETag); err != nil {
	return err
}

Python

Before trying this sample, follow the Python setup instructions in the BigQuery Quickstart Using Client Libraries . For more information, see the BigQuery Python API reference documentation .

# from google.cloud import bigquery
# client = bigquery.Client()
# project = 'my-project'
# source_dataset_id = 'my_source_dataset'
# source_table_id = 'us_states'
# shared_dataset_ref = client.dataset('my_shared_dataset')

# This example shows how to update a shared view of a source table of
# US States. The view's query will be updated to contain only states with
# names starting with 'M'.
view_ref = shared_dataset_ref.table("my_shared_view")
view = bigquery.Table(view_ref)
sql_template = 'SELECT name, post_abbr FROM `{}.{}.{}` WHERE name LIKE "M%"'
view.view_query = sql_template.format(project, source_dataset_id, source_table_id)
view = client.update_table(view, ["view_query"])  # API request

Updating a view's expiration time

You can set a default table expiration time at the dataset level (which affects both tables and views), or you can set a view's expiration time when the view is created. If you set the expiration when the view is created, the dataset's default table expiration is ignored. If you do not set a default table expiration at the dataset level, and you do not set an expiration when the view is created, the view never expires and you must delete the view manually.

At any point after the view is created, you can update the view's expiration time by:

  • Using the classic BigQuery web UI
    • Modifying view expiration times is not currently supported by the GCP Console
  • Using the CLI's bq update command
  • Calling the tables.patch API method
  • Using the client libraries

To update a view's expiration time:

Console

  1. In the navigation pane, select your view.

  2. On the view Details page, click the Details tab.

  3. To the right of View info, click the edit icon (pencil).

  4. In the View info dialog, for View expiration, click Specify date.

  5. In the date picker, enter the expiration date and time and then click Ok.

  6. Click Update. The updated expiration time appears in the View info section.

DDL

Data definition language (DDL) statements allow you to create and modify tables and views using standard SQL query syntax.

See more on Using Data Definition Language Statements.

To use a DDL statement in the GCP Console:

  1. Click Compose new query.

  2. Type your DDL statement into the Query editor text area.

    ALTER VIEW mydataset.myview
    SET OPTIONS (
    -- Sets view expiration to timestamp 2025-02-03 12:34:56 in the America/Los Angeles time zone
    expiration_timestamp=TIMESTAMP("2025-02-03 12:34:56", "America/Los Angeles")
    );
    
  3. Click Run query.

Classic UI

  1. In the navigation pane, select your view.

  2. On the View Details page, click Details.

  3. For Expiration Time, click Edit.

  4. In the Update Expiration dialog, click In and enter an expiration time in days.

  5. Click OK. The updated expiration time appears on the Details page.

    View expiration

CLI

Issue the bq update command with the --expiration flag. If you are updating a view in a project other than your default project, add the project ID to the dataset name in the following format: project_id:dataset.

bq update \
--expiration integer \
project_id:dataset.view

Where:

  • integer is the default lifetime (in seconds) for the table. The minimum value is 3600 seconds (one hour). The expiration time evaluates to the current time plus the integer value.
  • project_id is your project ID.
  • dataset is the name of the dataset that contains the view you're updating.
  • view is the name of the view you're updating.

Examples:

Enter the following command to update the expiration time of myview in mydataset to 5 days (43200 seconds). mydataset is in your default project.

bq update --expiration 432000 mydataset.myview

Enter the following command to update the expiration time of myview in mydataset to 5 days (43200 seconds). mydataset is in myotherproject, not your default project.

bq update --expiration 432000 myotherproject:mydataset.myview

API

Call the tables.patch method and use the expirationTime property in the table resource. Because the tables.update method replaces the entire table resource, the tables.patch method is preferred. When you use the REST API, the view's expiration is expressed in milliseconds.

Go

Before trying this sample, follow the Go setup instructions in the BigQuery Quickstart Using Client Libraries . For more information, see the BigQuery Go API reference documentation .

// To run this sample, you will need to create (or reuse) a context and
// an instance of the bigquery client.  For example:
// import "cloud.google.com/go/bigquery"
// ctx := context.Background()
// client, err := bigquery.NewClient(ctx, "your-project-id")
tableRef := client.Dataset(datasetID).Table(tableID)
meta, err := tableRef.Metadata(ctx)
if err != nil {
	return err
}
update := bigquery.TableMetadataToUpdate{
	ExpirationTime: time.Now().Add(time.Duration(5*24) * time.Hour), // table expiration in 5 days.
}
if _, err = tableRef.Update(ctx, update, meta.ETag); err != nil {
	return err
}

Node.js

Before trying this sample, follow the Node.js setup instructions in the BigQuery Quickstart Using Client Libraries . For more information, see the BigQuery Node.js API reference documentation .

// Import the Google Cloud client library
const {BigQuery} = require('@google-cloud/bigquery');
const bigquery = new BigQuery();

async function updateTableExpiration() {
  // Updates a table's expiration.

  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const datasetId = 'my_dataset', // Existing dataset
  // const tableId = 'my_table', // Existing table
  // const expirationTime = Date.now() + 1000 * 60 * 60 * 24 * 5 // 5 days from current time in ms

  // Retreive current table metadata
  const table = bigquery.dataset(datasetId).table(tableId);
  const [metadata] = await table.getMetadata();

  // Set new table expiration to 5 days from current time
  metadata.expirationTime = expirationTime.toString();
  const [apiResponse] = await table.setMetadata(metadata);

  const newExpirationTime = apiResponse.expirationTime;
  console.log(`${tableId} expiration: ${newExpirationTime}`);
}

Python

Updating a view's expiration is the same process as updating a table's expiration.

Before trying this sample, follow the Python setup instructions in the BigQuery Quickstart Using Client Libraries . For more information, see the BigQuery Python API reference documentation .

import datetime
import pytz

# from google.cloud import bigquery
# client = bigquery.Client()
# table_ref = client.dataset('my_dataset').table('my_table')
# table = client.get_table(table_ref)  # API request

assert table.expires is None

# set table to expire 5 days from now
expiration = datetime.datetime.now(pytz.utc) + datetime.timedelta(days=5)
table.expires = expiration
table = client.update_table(table, ["expires"])  # API request

# expiration is stored in milliseconds
margin = datetime.timedelta(microseconds=1000)
assert expiration - margin <= table.expires <= expiration + margin

Updating a view's description

You can update a view's description by:

  • Using the GCP Console or the classic BigQuery web UI
  • Using the bq update CLI command
  • Calling the tables.patch API method
  • Using the client libraries

To update a view's description:

Console

You cannot add a description when you create a view using the BigQuery web UI. After the view is created, you can add a description on the Details page.

  1. In the Resources list, select your view.

  2. Click over to the Details tab.

    View details

  3. Click the pencil icon next to Description.

    Edit view description

  4. Enter a description in the dialog box. Click Update to save the new description.

DDL

Data definition language (DDL) statements allow you to create and modify tables and views using standard SQL query syntax.

See more on Using Data Definition Language Statements.

To use a DDL statement in the GCP Console:

  1. Click Compose new query.

  2. Type your DDL statement into the Query editor text area.

     ALTER VIEW mydataset.myview
     SET OPTIONS (
       description="Description of myview"
     );
     

  3. Click Run query.

Classic UI

  1. In the navigation pane, select your view.

  2. On the View Details page, click Details.

  3. In the Description section, click Describe this view to open the description box.

  4. Enter a description in the box. When you click away from the box, the text is saved.

    Table description

CLI

Issue the bq update command with the --description flag. If you are updating a view in a project other than your default project, add the project ID to the dataset name in the following format: [PROJECT_ID]:[DATASET].

bq update \
--description "description" \
project_id:dataset.view

Where:

  • description is the text describing the view in quotes.
  • project_id is your project ID.
  • dataset is the name of the dataset that contains the view you're updating.
  • view is the name of the view you're updating.

Examples:

Enter the following command to change the description of myview in mydatasetto "Description of myview." mydataset is in your default project.

bq update --description "Description of myview" mydataset.myview

Enter the following command to change the description of myview in mydataset to "Description of myview." mydataset is in myotherproject, not your default project.

bq update \
--description "Description of myview" \
myotherproject:mydataset.myview

API

Call the tables.patch method and use the description property to update the view's description in the table resource. Because the tables.update method replaces the entire table resource, the tables.patch method is preferred.

Go

Before trying this sample, follow the Go setup instructions in the BigQuery Quickstart Using Client Libraries . For more information, see the BigQuery Go API reference documentation .

// To run this sample, you will need to create (or reuse) a context and
// an instance of the bigquery client.  For example:
// import "cloud.google.com/go/bigquery"
// ctx := context.Background()
// client, err := bigquery.NewClient(ctx, "your-project-id")
tableRef := client.Dataset(datasetID).Table(tableID)
meta, err := tableRef.Metadata(ctx)
if err != nil {
	return err
}
update := bigquery.TableMetadataToUpdate{
	Description: "Updated description.",
}
if _, err = tableRef.Update(ctx, update, meta.ETag); err != nil {
	return err
}

Java

Updating a view's description is the same process as updating a table's description.

Before trying this sample, follow the Java setup instructions in the BigQuery Quickstart Using Client Libraries . For more information, see the BigQuery Java API reference documentation .

// String datasetName = "my_dataset_name";
// String tableName = "my_table_name";
// String newDescription = "new_description";

Table beforeTable = bigquery.getTable(datasetName, tableName);
TableInfo tableInfo = beforeTable.toBuilder()
    .setDescription(newDescription)
    .build();
Table afterTable = bigquery.update(tableInfo);

Node.js

Before trying this sample, follow the Node.js setup instructions in the BigQuery Quickstart Using Client Libraries . For more information, see the BigQuery Node.js API reference documentation .

// Import the Google Cloud client library
const {BigQuery} = require('@google-cloud/bigquery');
const bigquery = new BigQuery();

async function updateTableDescription() {
  // Updates a table's description.

  // Retreive current table metadata
  const table = bigquery.dataset(datasetId).table(tableId);
  const [metadata] = await table.getMetadata();

  // Set new table description
  const description = 'New table description.';
  metadata.description = description;
  const [apiResponse] = await table.setMetadata(metadata);
  const newDescription = apiResponse.description;

  console.log(`${tableId} description: ${newDescription}`);
}

Python

Updating a view's description is the same process as updating a table's description.

Before trying this sample, follow the Python setup instructions in the BigQuery Quickstart Using Client Libraries . For more information, see the BigQuery Python API reference documentation .

# from google.cloud import bigquery
# client = bigquery.Client()
# table_ref = client.dataset('my_dataset').table('my_table')
# table = client.get_table(table_ref)  # API request

assert table.description == "Original description."
table.description = "Updated description."

table = client.update_table(table, ["description"])  # API request

assert table.description == "Updated description."

Next steps

Segítségére volt ez az oldal? Tudassa velünk a véleményét:

Visszajelzés küldése a következővel kapcsolatban:

Segítségre van szüksége? Keresse fel súgóoldalunkat.