Send a conditional write request. This type of write makes a CheckAndMutateRow API request.

## Explore further


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

- [Write examples](https://docs.cloud.google.com/bigtable/docs/writing-data)

## Code sample

### C++


To learn how to install and use the client library for Bigtable, see
[Bigtable client libraries](https://docs.cloud.google.com/bigtable/docs/reference/libraries).


To authenticate to Bigtable, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment).

    namespace cbt = ::google::cloud::bigtable;
    [](cbt::Table table) {
      auto timestamp = std::chrono::duration_cast<std::chrono::milliseconds>(
          std::chrono::system_clock::now().time_since_epoch());

      std::string row_key = "phone#4c410523#20190501";
      cbt::SingleRowMutation mutation(row_key);
      std::string column_family = "stats_summary";
      cbt::Filter predicate = cbt::Filter::Chain(
          cbt::Filter::ColumnName(column_family, "os_build"),
          cbt::Filter::Latest(1), cbt::Filter::ValueRegex("PQ2A\\..*"));

      google::cloud::StatusOr<cbt::MutationBranch> branch =
          table.CheckAndMutateRow(
              row_key, std::move(predicate),
              {cbt::SetCell(column_family, "os_name", timestamp, "android")}, {});

      if (!branch) throw std::move(branch).status();
      if (*branch == cbt::MutationBranch::kPredicateMatched) {
        std::cout << "Successfully updated row\n";
      } else {
        std::cout << "The predicate was not matched\n";
      }
    }

### C#


To learn how to install and use the client library for Bigtable, see
[Bigtable client libraries](https://docs.cloud.google.com/bigtable/docs/reference/libraries).


To authenticate to Bigtable, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment).


    using System;
    using https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Bigtable.V2/latest/Google.Cloud.Bigtable.V2.html;
    using https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Bigtable.Common.V2/latest/Google.Cloud.Bigtable.Common.V2.html;

    namespace Writes
    {
        public class WriteConditionalSample
        {
            /// <summary>
            /// Check if a row has a certain value then mutate the row if it does.
            ///</summary>
            /// <param name="projectId">Your Google Cloud Project ID.</param>
            /// <param name="instanceId">Your Google Cloud Bigtable Instance ID.</param>
            /// <param name="tableId">Your Google Cloud Bigtable table ID.</param>
            public string WriteConditional(
                string projectId = "YOUR-PROJECT-ID",
                string instanceId = "YOUR-INSTANCE-ID",
                string tableId = "YOUR-TABLE-ID")
            {
                https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Bigtable.V2/latest/Google.Cloud.Bigtable.V2.BigtableClient.html bigtableClient = https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Bigtable.V2/latest/Google.Cloud.Bigtable.V2.BigtableClient.html.https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Bigtable.V2/latest/Google.Cloud.Bigtable.V2.BigtableClient.html#Google_Cloud_Bigtable_V2_BigtableClient_Create();

                https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Bigtable.Common.V2/latest/Google.Cloud.Bigtable.Common.V2.TableName.html tableName = new https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Bigtable.Common.V2/latest/Google.Cloud.Bigtable.Common.V2.TableName.html(projectId, instanceId, tableId);
                https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Bigtable.Common.V2/latest/Google.Cloud.Bigtable.Common.V2.BigtableByteString.html rowkey = new https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Bigtable.Common.V2/latest/Google.Cloud.Bigtable.Common.V2.BigtableByteString.html("phone#4c410523#20190501");
                https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Bigtable.V2/latest/Google.Cloud.Bigtable.V2.BigtableVersion.html timestamp = new https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Bigtable.V2/latest/Google.Cloud.Bigtable.V2.BigtableVersion.html(DateTime.UtcNow);
                string COLUMN_FAMILY = "stats_summary";

                https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Bigtable.V2/latest/Google.Cloud.Bigtable.V2.CheckAndMutateRowResponse.html checkAndMutateRowResponse = bigtableClient.https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Bigtable.V2/latest/Google.Cloud.Bigtable.V2.BigtableClient.html#Google_Cloud_Bigtable_V2_BigtableClient_CheckAndMutateRow_Google_Cloud_Bigtable_Common_V2_TableName_Google_Cloud_Bigtable_Common_V2_BigtableByteString_Google_Cloud_Bigtable_V2_RowFilter_Google_Cloud_Bigtable_V2_Mutation___(
                    tableName,
                    rowkey,
                    https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Bigtable.V2/latest/Google.Cloud.Bigtable.V2.RowFilters.html.https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Bigtable.V2/latest/Google.Cloud.Bigtable.V2.RowFilters.html#Google_Cloud_Bigtable_V2_RowFilters_Chain_Google_Cloud_Bigtable_V2_RowFilter___(
                        https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Bigtable.V2/latest/Google.Cloud.Bigtable.V2.RowFilters.html.https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Bigtable.V2/latest/Google.Cloud.Bigtable.V2.RowFilters.html#Google_Cloud_Bigtable_V2_RowFilters_FamilyNameExact_System_String_(COLUMN_FAMILY),
                        https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Bigtable.V2/latest/Google.Cloud.Bigtable.V2.RowFilters.html.https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Bigtable.V2/latest/Google.Cloud.Bigtable.V2.RowFilters.html#Google_Cloud_Bigtable_V2_RowFilters_ColumnQualifierExact_Google_Cloud_Bigtable_Common_V2_BigtableByteString_("os_build"),
                        https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Bigtable.V2/latest/Google.Cloud.Bigtable.V2.RowFilters.html.https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Bigtable.V2/latest/Google.Cloud.Bigtable.V2.RowFilters.html#Google_Cloud_Bigtable_V2_RowFilters_ValueRegex_System_String_("PQ2A\\..*")),
                    https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Bigtable.V2/latest/Google.Cloud.Bigtable.V2.Mutations.html.https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Bigtable.V2/latest/Google.Cloud.Bigtable.V2.Mutations.html#Google_Cloud_Bigtable_V2_Mutations_SetCell_System_String_Google_Cloud_Bigtable_Common_V2_BigtableByteString_Google_Cloud_Bigtable_Common_V2_BigtableByteString_System_Nullable_Google_Cloud_Bigtable_V2_BigtableVersion__(COLUMN_FAMILY, "os_name", "android", timestamp));

                return $"Successfully updated row's os_name: {checkAndMutateRowResponse.https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Bigtable.V2/latest/Google.Cloud.Bigtable.V2.CheckAndMutateRowResponse.html#Google_Cloud_Bigtable_V2_CheckAndMutateRowResponse_PredicateMatched}";
            }
        }
    }

### Go


To learn how to install and use the client library for Bigtable, see
[Bigtable client libraries](https://docs.cloud.google.com/bigtable/docs/reference/libraries).


To authenticate to Bigtable, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment).

    import (
    	"context"
    	"fmt"
    	"io"

    	"cloud.google.com/go/bigtable"
    )

    func writeConditionally(w io.Writer, projectID, instanceID string, tableName string) error {
    	// projectID := "my-project-id"
    	// instanceID := "my-instance-id"
    	// tableName := "mobile-time-series"

    	ctx := context.Background()
    	client, err := bigtable.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/bigtable/latest/index.html#cloud_google_com_go_bigtable_Client_NewClient(ctx, projectID, instanceID)
    	if err != nil {
    		return fmt.Errorf("bigtable.NewAdminClient: %w", err)
    	}
    	defer client.Close()
    	tbl := client.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/bigtable/latest/index.html#cloud_google_com_go_bigtable_Client_Open(tableName)
    	columnFamilyName := "stats_summary"
    	timestamp := bigtable.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/bigtable/latest/index.html#cloud_google_com_go_bigtable_Timestamp_Now()

    	mut := bigtable.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/bigtable/latest/index.html#cloud_google_com_go_bigtable_Mutation_NewMutation()
    	mut.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/bigtable/latest/index.html#cloud_google_com_go_bigtable_Mutation_Set(columnFamilyName, "os_name", timestamp, []byte("android"))

    	filter := bigtable.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/bigtable/latest/index.html#cloud_google_com_go_bigtable_Filter_ChainFilters(
    		bigtable.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/bigtable/latest/index.html#cloud_google_com_go_bigtable_Filter_FamilyFilter(columnFamilyName),
    		bigtable.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/bigtable/latest/index.html#cloud_google_com_go_bigtable_Filter_ColumnFilter("os_build"),
    		bigtable.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/bigtable/latest/index.html#cloud_google_com_go_bigtable_Filter_ValueFilter("PQ2A\\..*"))
    	conditionalMutation := bigtable.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/bigtable/latest/index.html#cloud_google_com_go_bigtable_Mutation_NewCondMutation(filter, mut, nil)

    	rowKey := "phone#4c410523#20190501"
    	if err := tbl.Apply(ctx, rowKey, conditionalMutation); err != nil {
    		return fmt.Errorf("Apply: %w", err)
    	}

    	fmt.Fprintln(w, "Successfully updated row's os_name")
    	return nil
    }

### Java


To learn how to install and use the client library for Bigtable, see
[Bigtable client libraries](https://docs.cloud.google.com/bigtable/docs/reference/libraries).


To authenticate to Bigtable, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment).


    import static com.google.cloud.bigtable.data.v2.models.https://docs.cloud.google.com/java/docs/reference/google-cloud-bigtable/latest/com.google.cloud.bigtable.data.v2.models.Filters.html.FILTERS;

    import com.google.cloud.bigtable.data.v2.https://docs.cloud.google.com/java/docs/reference/google-cloud-bigtable/latest/com.google.cloud.bigtable.data.v2.BigtableDataClient.html;
    import com.google.cloud.bigtable.data.v2.models.https://docs.cloud.google.com/java/docs/reference/google-cloud-bigtable/latest/com.google.cloud.bigtable.data.v2.models.ConditionalRowMutation.html;
    import com.google.cloud.bigtable.data.v2.models.https://docs.cloud.google.com/java/docs/reference/google-cloud-bigtable/latest/com.google.cloud.bigtable.data.v2.models.Filters.html.Filter;
    import com.google.cloud.bigtable.data.v2.models.https://docs.cloud.google.com/java/docs/reference/google-cloud-bigtable/latest/com.google.cloud.bigtable.data.v2.models.Mutation.html;
    import com.google.cloud.bigtable.data.v2.models.https://docs.cloud.google.com/java/docs/reference/google-cloud-bigtable/latest/com.google.cloud.bigtable.data.v2.models.TableId.html;

    public class WriteConditionally {
      private static final String COLUMN_FAMILY_NAME = "stats_summary";

      public static void writeConditionally(String projectId, String instanceId, String tableId) {
        // String projectId = "my-project-id";
        // String instanceId = "my-instance-id";
        // String tableId = "mobile-time-series";

        try (https://docs.cloud.google.com/java/docs/reference/google-cloud-bigtable/latest/com.google.cloud.bigtable.data.v2.BigtableDataClient.html dataClient = https://docs.cloud.google.com/java/docs/reference/google-cloud-bigtable/latest/com.google.cloud.bigtable.data.v2.BigtableDataClient.html.create(projectId, instanceId)) {
          long timestamp = System.currentTimeMillis() * 1000;

          String rowkey = "phone#4c410523#20190501";

          https://docs.cloud.google.com/java/docs/reference/google-cloud-bigtable/latest/com.google.cloud.bigtable.data.v2.models.Mutation.html mutation =
              https://docs.cloud.google.com/java/docs/reference/google-cloud-bigtable/latest/com.google.cloud.bigtable.data.v2.models.Mutation.html.create().setCell(COLUMN_FAMILY_NAME, "os_name", timestamp, "android");

          Filter filter =
              FILTERS
                  .chain()
                  .filter(FILTERS.family().exactMatch(COLUMN_FAMILY_NAME))
                  .filter(FILTERS.qualifier().exactMatch("os_build"))
                  .filter(FILTERS.value().regex("PQ2A\\..*"));

          https://docs.cloud.google.com/java/docs/reference/google-cloud-bigtable/latest/com.google.cloud.bigtable.data.v2.models.ConditionalRowMutation.html conditionalRowMutation =
              https://docs.cloud.google.com/java/docs/reference/google-cloud-bigtable/latest/com.google.cloud.bigtable.data.v2.models.ConditionalRowMutation.html.create(https://docs.cloud.google.com/java/docs/reference/google-cloud-bigtable/latest/com.google.cloud.bigtable.data.v2.models.TableId.html.of(tableId), rowkey)
                  .condition(filter)
                  .then(mutation);

          boolean success = dataClient.https://docs.cloud.google.com/java/docs/reference/google-cloud-bigtable/latest/com.google.cloud.bigtable.data.v2.BigtableDataClient.html#com_google_cloud_bigtable_data_v2_BigtableDataClient_checkAndMutateRow_com_google_cloud_bigtable_data_v2_models_ConditionalRowMutation_(conditionalRowMutation);

          System.out.printf("Successfully updated row's os_name: %b", success);

        } catch (Exception e) {
          System.out.println("Error during WriteConditionally: \n" + e.toString());
          e.printStackTrace();
        }
      }
    }

### PHP


To learn how to install and use the client library for Bigtable, see
[Bigtable client libraries](https://docs.cloud.google.com/bigtable/docs/reference/libraries).


To authenticate to Bigtable, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment).

    use Google\Cloud\Bigtable\BigtableClient;
    use Google\Cloud\Bigtable\Filter;
    use Google\Cloud\Bigtable\Mutations;

    /**
     * Write data conditionally in a table
     *
     * @param string $projectId The Google Cloud project ID
     * @param string $instanceId The ID of the Bigtable instance
     * @param string $tableId The ID of the table where the data needs to be written
     */
    function write_conditionally(
        string $projectId,
        string $instanceId,
        string $tableId = 'mobile-time-series'
    ): void {
        // Connect to an existing table with an existing instance.
        $dataClient = new BigtableClient([
            'projectId' => $projectId,
        ]);
        $table = $dataClient->table($instanceId, $tableId);

        $timestampMicros = time() * 1000 * 1000;
        $columnFamilyId = 'stats_summary';

        $mutations = (new Mutations())->upsert($columnFamilyId, 'os_name', 'android', $timestampMicros);
        $predicateFilter = Filter::chain()
        ->addFilter(Filter::family()->exactMatch($columnFamilyId))
        ->addFilter(Filter::qualifier()->exactMatch('os_build'))
        ->addFilter(Filter::value()->regex('PQ2A.*'));
        $options = ['predicateFilter' => $predicateFilter, 'trueMutations' => $mutations];

        $table->checkAndMutateRow('phone#4c410523#20190501', $options);

        printf('Successfully updated row\'s os_name' . PHP_EOL);
    }

### Python


To learn how to install and use the client library for Bigtable, see
[Bigtable client libraries](https://docs.cloud.google.com/bigtable/docs/reference/libraries).


To authenticate to Bigtable, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment).

    from google.cloud.bigtable.data import BigtableDataClient, https://docs.cloud.google.com/python/docs/reference/bigtable/latest/google.cloud.bigtable.data.mutations.SetCell.html, https://docs.cloud.google.com/python/docs/reference/bigtable/latest/google.cloud.bigtable.data.row_filters.html

    def write_conditional(project_id, instance_id, table_id):
        with BigtableDataClient(project=project_id) as client:
            with client.get_table(instance_id, table_id) as table:
                family_id = "stats_summary"
                row_key = "phone#4c410523#20190501"

                row_filter = https://docs.cloud.google.com/python/docs/reference/bigtable/latest/google.cloud.bigtable.data.row_filters.html.https://docs.cloud.google.com/python/docs/reference/bigtable/latest/google.cloud.bigtable.data.row_filters.RowFilterChain.html(
                    filters=[
                        https://docs.cloud.google.com/python/docs/reference/bigtable/latest/google.cloud.bigtable.data.row_filters.html.https://docs.cloud.google.com/python/docs/reference/bigtable/latest/google.cloud.bigtable.data.row_filters.FamilyNameRegexFilter.html(family_id),
                        https://docs.cloud.google.com/python/docs/reference/bigtable/latest/google.cloud.bigtable.data.row_filters.html.https://docs.cloud.google.com/python/docs/reference/bigtable/latest/google.cloud.bigtable.data.row_filters.ColumnQualifierRegexFilter.html("os_build"),
                        https://docs.cloud.google.com/python/docs/reference/bigtable/latest/google.cloud.bigtable.data.row_filters.html.https://docs.cloud.google.com/python/docs/reference/bigtable/latest/google.cloud.bigtable.data.row_filters.ValueRegexFilter.html("PQ2A\\..*"),
                    ]
                )

                if_true = SetCell(family_id, "os_name", "android")
                result = table.check_and_mutate_row(
                    row_key,
                    row_filter,
                    true_case_mutations=if_true,
                    false_case_mutations=None,
                )
                if result is True:
                    print("The row os_name was set to android")

### Ruby


To learn how to install and use the client library for Bigtable, see
[Bigtable client libraries](https://docs.cloud.google.com/bigtable/docs/reference/libraries).


To authenticate to Bigtable, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment).

    # instance_id = "my-instance"
    # table_id    = "my-table"
    table = bigtable.table instance_id, table_id
    column_family = "stats_summary"
    timestamp = (Time.now.to_f * 1_000_000).round(-3)

    rowkey = "phone#4c410523#20190501"
    predicate_filter = Google::Cloud::Bigtable::RowFilter.chain
                                                         .family(column_family)
                                                         .qualifier("os_build")
                                                         .value("PQ2A\\..*")

    on_match_mutations = Google::Cloud::Bigtable::MutationEntry.new
    on_match_mutations.set_cell(
      column_family,
      "os_name",
      "android",
      timestamp: timestamp
    )

    response = table.check_and_mutate_row(
      rowkey,
      predicate_filter,
      on_match: on_match_mutations
    )

    puts "Successfully updated row's os_name: #{response}"

## What's next


To search and filter code samples for other Google Cloud products, see the
[Google Cloud sample browser](https://docs.cloud.google.com/docs/samples?product=bigtable).