Adding labels to resources

This page explains how to label your BigQuery resources.

Before you begin

Grant Identity and Access Management (IAM) roles that give users the necessary permissionsto perform each task in this document. Any permissions required to perform atask are listed in the "Required IAM roles" section of the task.

Add labels to datasets

A label can be added to a BigQuery dataset when it is created byusing the bq command-line tool'sbq mk command or by calling thedatasets.insert APImethod. You cannot add a label to a dataset when it's created usingthe Google Cloud console.

This page discusses how to add a label to a dataset after it is created. Formore information on adding a label when you create a dataset, seeCreating a dataset.

When you add a label to a dataset, it does not propagate to resources within thedataset. Dataset labels are not inherited by tables or views. Also, when you adda label to a dataset, it is included in your storage billing data, but not inyour job-related billing data.

For more details on the format of a label, seeRequirements for labels.

Required IAM roles

To get the permission that you need to add a label to an existing dataset, ask your administrator to grant you theBigQuery Data Owner (roles/bigquery.dataOwner) IAM role. For more information about granting roles, seeManage access to projects, folders, and organizations.

This predefined role contains the bigquery.datasets.update permission, which is required to add a label to an existing dataset.

You might also be able to get this permission withcustom roles or otherpredefined roles.

For more information on IAM roles and permissions inBigQuery, seePredefined roles and permissions.

Add a label to a dataset

To add a label to a dataset after it is created:

Console

  1. In the Google Cloud console, select the dataset.

  2. On the dataset details page, click the pencil icon to the right ofLabels.

    Label pencil.

  3. In theEdit labels dialog:

    • ClickAdd label
    • Enter the key and value. To apply additional labels,clickAdd label. Each key can be used only once per dataset,but you can use the same key in different datasets in the sameproject.
    • To update a label, modify the existing keys or values.
    • To save your changes, clickUpdate.

SQL

Use theALTER SCHEMA SET OPTIONS DDL statementto set the labels on an existing dataset. Setting labels overwrites anyexisting labels on the dataset. The following example sets a label on thedatasetmydataset:

  1. In the Google Cloud console, go to theBigQuery page.

    Go to BigQuery

  2. In the query editor, enter the following statement:

    ALTERSCHEMAmydatasetSETOPTIONS(labels=[('sensitivity','high')]);

  3. ClickRun.

For more information about how to run queries, seeRun an interactive query.

bq

To add a label to an existing dataset, issue thebq update command withtheset_label flag. Repeat the flag to add multiple labels.

If the dataset is in a project other than your default project, add theproject ID to the dataset in the following format:PROJECT_ID:DATASET.

bqupdate--set_labelKEY:VALUEPROJECT_ID:DATASET

Replace the following:

  • KEY:VALUE: a key-value pair for a label that youwant to add. The key must be unique. Keys and values can contain onlylowercase letters, numeric characters, underscores, and dashes. Allcharacters must use UTF-8 encoding, and international characters areallowed.
  • PROJECT_ID: your project ID.
  • DATASET: the dataset you're labeling.

Examples:

To add a label to track departments, enter thebq update command andspecifydepartment as the label key. For example, to add adepartment:shipping label tomydataset in your default project, enter:

    bq update --set_label department:shipping mydataset

To add multiple labels to a dataset, repeat theset_label flag and specifya unique key for each label. For example, to add adepartment:shippinglabel andcost_center:logistics label tomydataset in your defaultproject, enter:

    bq update \    --set_label department:shipping \    --set_label cost_center:logistics \    mydataset

API

To add a label to an existing dataset, call thedatasets.patchmethod and populate thelabels property for thedataset resource.

Because thedatasets.update method replaces the entire dataset resource,thedatasets.patch method is preferred.

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")// addDatasetLabel demonstrates adding label metadata to an existing dataset.funcaddDatasetLabel(projectID,datasetIDstring)error{// projectID := "my-project-id"// datasetID := "mydataset"ctx:=context.Background()client,err:=bigquery.NewClient(ctx,projectID)iferr!=nil{returnfmt.Errorf("bigquery.NewClient: %v",err)}deferclient.Close()ds:=client.Dataset(datasetID)meta,err:=ds.Metadata(ctx)iferr!=nil{returnerr}update:=bigquery.DatasetMetadataToUpdate{}update.SetLabel("color","green")if_,err:=ds.Update(ctx,update,meta.ETag);err!=nil{returnerr}returnnil}

Java

This sample uses theGoogle HTTP Client Library for Javato send a request to the BigQuery API.

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.Dataset;importjava.util.HashMap;importjava.util.Map;// Sample to updates a label on datasetpublicclassLabelDataset{publicstaticvoidmain(String[]args){// TODO(developer): Replace these variables before running the sample.StringdatasetName="MY_DATASET_NAME";labelDataset(datasetName);}publicstaticvoidlabelDataset(StringdatasetName){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();// This example dataset starts with existing label { color: 'green' }Datasetdataset=bigquery.getDataset(datasetName);// Add label to datasetMap<String,String>labels=newHashMap<>();labels.put("color","green");dataset.toBuilder().setLabels(labels).build().update();System.out.println("Label added successfully");}catch(BigQueryExceptione){System.out.println("Label was not added. \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();asyncfunctionlabelDataset(){// Updates a label on a dataset./**   * TODO(developer): Uncomment the following lines before running the sample   */// const datasetId = "my_dataset";// Retrieve current dataset metadata.constdataset=bigquery.dataset(datasetId);const[metadata]=awaitdataset.getMetadata();// Add label to dataset metadatametadata.labels={color:'green'};const[apiResponse]=awaitdataset.setMetadata(metadata);console.log(`${datasetId} labels:`);console.log(apiResponse.labels);}

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 dataset_id to the ID of the dataset to fetch.# dataset_id = "your-project.your_dataset"dataset=client.get_dataset(dataset_id)# Make an API request.dataset.labels={"color":"green"}dataset=client.update_dataset(dataset,["labels"])# Make an API request.print("Labels added to{}".format(dataset_id))

Add labels to tables and views

This page discusses how to add a label to an existing table or view. For moreinformation on adding a label when you create a table or view, seeCreating a table orCreating a view.

Because views are treated like table resources, you use thetables.patchmethod to modify both views and tables.

Note: Table and view labels are not included in billing data.

Required IAM roles

To get the permissions that you need to add a label to an existing table or view, ask your administrator to grant you theBigQuery Data Editor (roles/bigquery.dataEditor) IAM role. For more information about granting roles, seeManage access to projects, folders, and organizations.

This predefined role contains the permissions required to add a label to an existing table or view. To see the exact permissions that are required, expand theRequired permissions section:

Required permissions

The following permissions are required to add a label to an existing table or view:

  • bigquery.tables.update
  • bigquery.tables.get

You might also be able to get these permissions withcustom roles or otherpredefined roles.

For more information on IAM roles and permissions inBigQuery, seePredefined roles and permissions.

Add a label to a table or view

To add a label to an existing table or view:

Console

  1. In the Google Cloud console, select the table, or view.

  2. Click theDetails tab.

    Table details.

  3. Click the pencil icon to the right ofLabels.

    Label pencil.

  4. In theEdit labels dialog:

    • ClickAdd label
    • Enter your key and value to add a label. To apply additional labels,clickAdd label. Each key can be used only once per dataset,but you can use the same key in different datasets in the same project.
    • Modify existing keys or values to update a label.
    • ClickUpdate to save your changes.

SQL

Use theALTER TABLE SET OPTIONS DDL statementto set the labels on an existing table, or theALTER VIEW SET OPTIONS DDL statementto set the labels on an existing view. Setting labels overwrites anyexisting labels on the table or view. The following example sets two labelson the tablemytable:

  1. In the Google Cloud console, go to theBigQuery page.

    Go to BigQuery

  2. In the query editor, enter the following statement:

    ALTERTABLEmydataset.mytableSETOPTIONS(labels=[('department','shipping'),('cost_center','logistics')]);

  3. ClickRun.

For more information about how to run queries, seeRun an interactive query.

bq

To add a label to an existing table or view, issue thebq update commandwith theset_label flag. To add multiple labels, repeat the flag.

If the table or view is in a project other than your default project, addthe project ID to the dataset in the following format:project_id:dataset.

bqupdate\--set_labelKEY:VALUE\PROJECT_ID:DATASET.TABLE_OR_VIEW

Replace the following:

  • KEY:VALUE: a key-value pair for a label that youwant to add. The key must be unique. Keys and values can contain onlylowercase letters, numeric characters, underscores, and dashes. Allcharacters must use UTF-8 encoding, and international characters areallowed.
  • PROJECT_ID: your project ID.
  • DATASET: the dataset that contains the table orview you're labeling.
  • TABLE_OR_VIEW: the name of the table or viewyou're labeling.

Examples:

To add a table label that tracks departments, enter thebq update commandand specifydepartment as the label key. For example, to add adepartment:shipping label tomytable in your default project, enter:

    bq update --set_label department:shipping mydataset.mytable

To add a view label that tracks departments, enter thebq update commandand specifydepartment as the label key. For example, to add adepartment:shipping label tomyview in your default project, enter:

    bq update --set_label department:shipping mydataset.myview

To add multiple labels to a table or view, repeat theset_label flag andspecify a unique key for each label. For example, to add adepartment:shipping label andcost_center:logistics label tomytablein your default project, enter:

    bq update \    --set_label department:shipping \    --set_label cost_center:logistics \    mydataset.mytable

API

To add a label to an existing table or view, call thetables.patchmethod and populate thelabels property for thetable resource.

Because views are treated like table resources, you use thetables.patchmethod to modify both views and tables.

Because thetables.update method replaces the entire dataset resource, thetables.patch method is preferred.

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")// addTableLabel demonstrates adding Label metadata to a BigQuery table.funcaddTableLabel(projectID,datasetID,tableIDstring)error{// projectID := "my-project-id"// datasetID := "mydataset"// tableID := "mytable"ctx:=context.Background()client,err:=bigquery.NewClient(ctx,projectID)iferr!=nil{returnfmt.Errorf("bigquery.NewClient: %v",err)}deferclient.Close()tbl:=client.Dataset(datasetID).Table(tableID)meta,err:=tbl.Metadata(ctx)iferr!=nil{returnerr}update:=bigquery.TableMetadataToUpdate{}update.SetLabel("color","green")if_,err:=tbl.Update(ctx,update,meta.ETag);err!=nil{returnerr}returnnil}

Java

This sample uses theGoogle HTTP Client Library for Javato send a request to the BigQuery API.

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.Table;importcom.google.cloud.bigquery.TableId;importjava.util.HashMap;importjava.util.Map;// Sample to adds a label to an existing tablepublicclassLabelTable{publicstaticvoidmain(String[]args){// TODO(developer): Replace these variables before running the sample.StringdatasetName="MY_DATASET_NAME";StringtableName="MY_TABLE_NAME";labelTable(datasetName,tableName);}publicstaticvoidlabelTable(StringdatasetName,StringtableName){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();// This example table starts with existing label { color: 'green' }Tabletable=bigquery.getTable(TableId.of(datasetName,tableName));// Add label to tableMap<String,String>labels=newHashMap<>();labels.put("color","green");table.toBuilder().setLabels(labels).build().update();System.out.println("Label added successfully");}catch(BigQueryExceptione){System.out.println("Label was not added. \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();asyncfunctionlabelTable(){// Adds a label to an existing table./**   * TODO(developer): Uncomment the following lines before running the sample.   */// const datasetId = 'my_dataset';// const tableId = 'my_table';constdataset=bigquery.dataset(datasetId);const[table]=awaitdataset.table(tableId).get();// Retrieve current table metadataconst[metadata]=awaittable.getMetadata();// Add label to table metadatametadata.labels={color:'green'};const[apiResponse]=awaittable.setMetadata(metadata);console.log(`${tableId} labels:`);console.log(apiResponse.labels);}

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"table=client.get_table(table_id)# API requestlabels={"color":"green"}table.labels=labelstable=client.update_table(table,["labels"])# API requestprint(f"Added{table.labels} to{table_id}.")

Add labels to jobs

Labels can be added to query jobs through the command line by using thebq command-line tool's--label flag. The bq tool supports addinglabels only to query jobs.

You can also add a label to a job when it's submitted through the API by specifyingthelabels property in the job configuration when you call thejobs.insert method. The APIcan be used to add labels to any job type.

You cannot add labels to or update labels on pending, running, or completedjobs.

When you add a label to a job, the label is included in your billing data.

Required IAM roles

To get the permission that you need to add a label to a job, ask your administrator to grant you theBigQuery User (roles/bigquery.user) IAM role. For more information about granting roles, seeManage access to projects, folders, and organizations.

This predefined role contains the bigquery.jobs.create permission, which is required to add a label to a job.

You might also be able to get this permission withcustom roles or otherpredefined roles.

For more information on IAM roles and permissions inBigQuery, seePredefined roles and permissions.

Add a label to a job

To add a label to a job:

bq

To add a label to a query job, issue thebq query command withthe--label flag. To add multiple labels, repeat the flag. The flag indicates that your query is in GoogleSQLsyntax.

bqquery--labelKEY:VALUE'QUERY'

Replace the following:

  • KEY:VALUE: a key-value pair for a label that youwant to add to the query job. The key must be unique. Keys and values cancontain only lowercase letters, numeric characters, underscores, anddashes. All characters must use UTF-8 encoding, and internationalcharacters are allowed. To add multiple labels to a query job, repeat the--label flag and specify a unique keyfor each label.
  • QUERY: a valid GoogleSQL query.

Examples:

To add a label to a query job, enter:

    bq query \    --label department:shipping \     \    'SELECT       column1, column2     FROM       `mydataset.mytable`'

To add multiple labels to a query job, repeat the--label flag andspecify a unique key for each label. For example, to add adepartment:shipping label andcost_center:logistics label to a queryjob, enter:

    bq query \    --label department:shipping \    --label cost_center:logistics \     \    'SELECT       column1, column2     FROM`mydataset.mytable`'

API

To add a label to a job, call thejobs.insertmethod and populate thelabels property for thejob configuration.You can use the API to add labels to any job type.

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()sql="""    SELECT corpus    FROM `bigquery-public-data.samples.shakespeare`    GROUP BY corpus;"""labels={"color":"green"}config=bigquery.QueryJobConfig()config.labels=labelslocation="us"job=client.query(sql,location=location,job_config=config)job_id=job.job_idprint(f"Added{job.labels} to{job_id}.")

Associate jobs in a session with a label

If you are running queries in asession, you can assign a label toall future query jobs in the session using BigQuerymulti-statement queries.

SQL

Set the@@query_labelsystem variable in the session by running this query:

SET@@query_label="KEY:VALUE";

  • KEY:VALUE: a key-value pair for the label to assign to all futurequeries in the session. You can also add multiple key-value pairs, separatedby a comma (for example,SET @@query_label = "key1:value1,key2:value2").The key must be unique. Keys and values can contain only lowercase letters,numeric characters, underscores, and dashes. All characters must use UTF-8encoding, and international characters are allowed.

Example:

SET@@query_label="cost_center:logistics";

API

To add a label to a query job in a session when yourun a query using an API call, callthejobs.insertmethod and populate thequery_label property for theconnectionPropertiesjob configuration.

After you have associated a query label with a session and run queries insidethe session, you can collect audit logs for queries with that query label.For more information, see theAudit log reference for BigQuery.

Add a label to a reservation

When you add a label to a reservation, the label is included in your billingdata. You can use the labels to filter the Analysis Slots Attribution SKU inyour Cloud Billing data.

The Analysis Slots Attribution SKU only records slot usage. It doesn't recordcosts for BigQuery Reservation API SKUs. Reservation labels aren't supported asfilters for BigQuery Reservation API SKUs.

For more information about using labels in your billing data, seeUseFilters to refine data.

Required IAM roles

To get the permission that you need to add a label to a reservation, ask your administrator to grant you theBigQuery Resource Editor (roles/bigquery.resourceEditor) IAM role on the administration project. For more information about granting roles, seeManage access to projects, folders, and organizations.

This predefined role contains the bigquery.reservations.update permission, which is required to add a label to a reservation.

You might also be able to get this permission withcustom roles or otherpredefined roles.

Add a label to a reservation

To add a label to a reservation:

Console

  1. In the Google Cloud console, go to the BigQuery page.

    Go to BigQuery

  2. In the navigation menu, clickCapacity management.

  3. Click theSlot reservations tab.

  4. Find the reservation you want to update.

  5. Expand theActions option.

  6. ClickEdit.

  7. To expand theAdvanced settings section, click theexpander arrow.

  8. ClickAdd Label.

  9. Enter the key-value pair. To apply additional labels, clickAdd label.

  10. ClickSave.

SQL

To add a label to a reservation, use theALTER RESERVATION SET OPTIONSDDLstatement.Setting labels overwrites any existing labels on the reservation. Thefollowing example sets a label on the reservationmyreservation:

  1. In the Google Cloud console, go to theBigQuery page.

    Go to BigQuery

  2. In the query editor, enter the following statement:

    ALTERRESERVATIONmyreservationSETOPTIONS(labels=[('sensitivity','high')]);

  3. ClickRun.

For more information about how to run queries, seeRun an interactive query.

bq

To add a label to a reservation, issue thebq update command with theset_label flag and the--reservation flag. To add multiple labels, repeattheset_label flag.

bqupdate--set_labelKEY:VALUE--locationLOCATION--reservationRESERVATION_NAME

Replace the following:

  • KEY:VALUE: a key-value pair for a label that youwant to add to the reservation. The key must be unique. Keys and values cancontain only lowercase letters, numeric characters, underscores, anddashes. All characters must use UTF-8 encoding, and internationalcharacters are allowed. To add multiple labels to a reservation, repeat the--set_label flag and specify a unique keyfor each label.
  • LOCATION: the location of the reservation.Thelocation flag can't be last in the command,otherwise theFATAL Flags positioning erroris returned.
  • RESERVATION_NAME: the name of the reservation.

Add a label without a value

A label that has a key with an empty value is sometimes called a tag. Thisshouldn't be confused with atag resource. For moreinformation, seelabels and tags.You can create a new label with no value, or you can remove a value from anexisting label key.

Labels without values can be useful in situations where you are labeling aresource, but you don't need the key-value format. For example, if a tablecontains test data that is used by multiple groups, such as support ordevelopment, you can add atest_data label to the table to identify it.

To add a label without a value:

Console

  1. In the Google Cloud console, select the appropriate resource (adataset, table, or view).

  2. For datasets, the dataset details page is automatically opened. Fortables and views, clickDetails to open the details page.

    Table details.

  3. On the details page, click the pencil icon to the right ofLabels.

    Label pencil.

  4. In theEdit labels dialog:

    • ClickAdd label.
    • Enter a new key and leave the value blank. To apply additional labels,clickAdd label and repeat.
    • To save your changes, clickUpdate.

SQL

To add a label without a value, use theALTER TABLE SET OPTIONS DDL statement:

  1. In the Google Cloud console, go to theBigQuery page.

    Go to BigQuery

  2. In the query editor, enter the following statement:

    ALTERTABLEmydataset.mytableSETOPTIONS(labels=[("key1",""),("key2","")]);

  3. ClickRun.

For more information about how to run queries, seeRun an interactive query.

bq

To add a label without a value to an existing resource, use thebq update command with theset_label flag. Specify the key, followed by a colon, but leave the valueunspecified.

bqupdate--set_labelKEY:RESOURCE_ID

Replace the following:

  • KEY:: the label key that you want to use.
  • RESOURCE_ID: a valid dataset, table, or view name.If the resource is in a project other than your default project, add theproject ID in the following format:PROJECT_ID:DATASET.

Examples:

Enter the following command to create atest_data label formydataset.mytable.mydataset is in your default project.

bq update --set_label test_data: mydataset

API

Call thedatasets.patchmethod or thetables.patchmethod and add labels with the value set to the empty string ("") in thedataset resourceor thetable resource.You can remove values from existing labels by replacing their values withthe empty string.

Because views are treated like table resources, you use thetables.patchmethod to modify both views and tables. Also, because thetables.updatemethod replaces the entire dataset resource, thetables.patch method ispreferred.

What's next

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.

Last updated 2026-02-18 UTC.