Deleting Data in Azure Table Storage

On this page:

Introduction

Azure Table Storage is a NoSQL key-value store that can store large amounts of structured data. When managing your data, you may need to delete specific entities or even entire tables. This document outlines the methods for deleting data in Azure Table Storage.

Before proceeding, ensure you have the necessary permissions to perform delete operations on your Azure Storage account.

Deletion Methods

Deleting a Single Entity

You can delete a single entity from a table by providing its PartitionKey and RowKey. This is the most common and granular way to remove data.

C# Example (using Azure.Data.Tables SDK)

using Azure;
using Azure.Data.Tables;

// Replace with your connection string and table name
string connectionString = "";
string tableName = "MySampleTable";
string partitionKey = "Group1";
string rowKey = "Item1";

TableServiceClient tableServiceClient = new TableServiceClient(connectionString);
TableClient tableClient = tableServiceClient.GetTableClient(tableName);

// Ensure the table exists
tableClient.CreateIfNotExists();

// Delete the entity
Response response = tableClient.DeleteEntity(partitionKey, rowKey);

if (response.Status == 204)
{
    Console.WriteLine($"Entity with PartitionKey='{partitionKey}' and RowKey='{rowKey}' deleted successfully.");
}
else
{
    Console.WriteLine($"Failed to delete entity. Status code: {response.Status}");
}
                    
Python Example (using azure-data-tables SDK)

from azure.data.tables import TableServiceClient

# Replace with your connection string and table name
connection_string = ""
table_name = "MySampleTable"
partition_key = "Group1"
row_key = "Item1"

table_service_client = TableServiceClient.from_connection_string(connection_string)
table_client = table_service_client.get_table_client(table_name)

# Ensure the table exists
table_client.create_table()

# Delete the entity
try:
    table_client.delete_entity(partition_key, row_key)
    print(f"Entity with PartitionKey='{partition_key}' and RowKey='{row_key}' deleted successfully.")
except Exception as ex:
    print(f"Failed to delete entity: {ex}")
                    
Azure CLI Example

# Log in to Azure if you haven't already
# az login

# Replace with your storage account name, resource group, table name, partition key, and row key
STORAGE_ACCOUNT_NAME="yourstorageaccountname"
RESOURCE_GROUP="yourresourcegroup"
TABLE_NAME="MySampleTable"
PARTITION_KEY="Group1"
ROW_KEY="Item1"

az storage table entity delete \
    --account-name $STORAGE_ACCOUNT_NAME \
    --table-name $TABLE_NAME \
    --partition-key $PARTITION_KEY \
    --row-key $ROW_KEY \
    --auth-mode login # Or use --connection-string ""
                    

Deleting Multiple Entities (Batch Delete)

For efficiency, you can delete multiple entities within a single batch operation. This is particularly useful when you need to remove a set of related entities that share the same PartitionKey.

Note: Batch operations in Azure Table Storage are limited to entities within the same partition. You cannot perform a batch operation across different partition keys.

C# Example (Batch Delete)

using Azure;
using Azure.Data.Tables;
using System.Collections.Generic;

// Replace with your connection string and table name
string connectionString = "";
string tableName = "MySampleTable";
string partitionKey = "Group1";

TableServiceClient tableServiceClient = new TableServiceClient(connectionString);
TableClient tableClient = tableServiceClient.GetTableClient(tableName);
tableClient.CreateIfNotExists();

// Prepare entities to delete (only PartitionKey and RowKey are needed for delete)
var entitiesToDelete = new List<TableTransactionAction>
{
    new TableTransactionAction(TableTransactionActionType.Delete, new TableEntity(partitionKey, "Item1")),
    new TableTransactionAction(TableTransactionActionType.Delete, new TableEntity(partitionKey, "Item2")),
    new TableTransactionAction(TableTransactionActionType.Delete, new TableEntity(partitionKey, "Item3"))
};

// Submit the batch
try
{
    Response<IReadOnlyList<Response>> response = tableClient.SubmitTransaction(entitiesToDelete, CancellationToken.None);

    if (response.Value.All(r => r.Status == 204))
    {
        Console.WriteLine($"Batch delete operation for PartitionKey='{partitionKey}' completed successfully.");
    }
    else
    {
        Console.WriteLine("Some entities in the batch delete operation may not have been deleted.");
        for (int i = 0; i < response.Value.Count; i++)
        {
            if (response.Value[i].Status != 204)
            {
                Console.WriteLine($"  Entity index {i}: Status {response.Value[i].Status}");
            }
        }
    }
}
catch (RequestFailedException ex)
{
    Console.WriteLine($"Batch delete operation failed: {ex.Message}");
}
                    
Python Example (Batch Delete)

from azure.data.tables import TableServiceClient, TableTransactionAction

# Replace with your connection string and table name
connection_string = ""
table_name = "MySampleTable"
partition_key = "Group1"

table_service_client = TableServiceClient.from_connection_string(connection_string)
table_client = table_service_client.get_table_client(table_name)
table_client.create_table()

# Prepare entities to delete (only PartitionKey and RowKey are needed for delete)
entities_to_delete = [
    TableTransactionAction("delete", {"PartitionKey": partition_key, "RowKey": "Item1"}),
    TableTransactionAction("delete", {"PartitionKey": partition_key, "RowKey": "Item2"}),
    TableTransactionAction("delete", {"PartitionKey": partition_key, "RowKey": "Item3"})
]

# Submit the batch
try:
    responses = table_client.submit_transaction(entities_to_delete)
    all_deleted = True
    for i, response in enumerate(responses):
        if response.get("status") != 204:
            print(f"Entity at index {i} not deleted. Status: {response.get('status')}")
            all_deleted = False
    if all_deleted:
        print(f"Batch delete operation for PartitionKey='{partition_key}' completed successfully.")
except Exception as ex:
    print(f"Batch delete operation failed: {ex}")
                    

Deleting an Entire Table

If you no longer need a table and all its contents, you can delete the entire table. This operation is irreversible.

C# Example (Delete Table)

using Azure;
using Azure.Data.Tables;

// Replace with your connection string and table name
string connectionString = "";
string tableName = "MyOldTable";

TableServiceClient tableServiceClient = new TableServiceClient(connectionString);

// Delete the table
Response response = tableServiceClient.DeleteTable(tableName);

if (response.Status == 204)
{
    Console.WriteLine($"Table '{tableName}' deleted successfully.");
}
else
{
    Console.WriteLine($"Failed to delete table '{tableName}'. Status code: {response.Status}");
}
                    
Python Example (Delete Table)

from azure.data.tables import TableServiceClient

# Replace with your connection string and table name
connection_string = ""
table_name = "MyOldTable"

table_service_client = TableServiceClient.from_connection_string(connection_string)

# Delete the table
try:
    table_client = table_service_client.get_table_client(table_name)
    table_client.delete_table()
    print(f"Table '{table_name}' deleted successfully.")
except Exception as ex:
    print(f"Failed to delete table '{table_name}': {ex}")
                    
Azure CLI Example

# Replace with your storage account name and table name
STORAGE_ACCOUNT_NAME="yourstorageaccountname"
TABLE_NAME="MyOldTable"

az storage table delete \
    --account-name $STORAGE_ACCOUNT_NAME \
    --name $TABLE_NAME \
    --auth-mode login # Or use --connection-string ""
                    

Important Considerations

Irreversibility: Deleting data in Azure Table Storage, especially entire tables, is generally irreversible. Once deleted, the data is permanently lost. Always ensure you have backups or have confirmed the necessity of deletion before proceeding.

Concurrency: When deleting entities, be mindful of concurrent operations. Use ETag matching if you need to ensure you are deleting the correct version of an entity and not overwriting changes made by another client.

For more advanced scenarios or specific error handling, refer to the official Azure Table Storage documentation for the SDK or tool you are using.